microsoft / microsoft/TypeScript
Inference isn't working with constructor that contextually types 'this' with intersections of itself
Personne n'a encore pris cette issue.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.4k
- Merge moyen
- 1 j 19 h
- PR mergées (30 j)
- 117
Description
TL;DR: There should be no errors in the below example.
I am trying to model a library that takes an options bag for its constructor, and exposes those properties onto the instance that is eventually produced.
For example, if I wrote
let instance = new Component({
methods: {
hello() { }
world() {
this.hello();
}
}
});
I should be able to write instance.hello() or instance.world().
Additionally, since this in world will be bound to the instance, this.hello should be legal and well-typed in the above example.
However, I'm not able to come up with a version of this that works.
/**
* Ensures all properties have a `this` param of type `T`.
*/
interface ThisEnforced<T> {
[prop: string]: (this: T, ...args: any[]) => any;
}
interface ComponentOptions<Methods> {
methods?: Methods
}
interface Component<Methods extends ThisEnforced<Component<Methods> & Methods>> {
$methods: Methods;
}
interface ComponentStatic {
new <Methods extends ThisEnforced<Component<Methods> & Methods>>(options: ComponentOptions<Methods>):
// Returns...
Component<Methods> & Methods;
}
declare var Component: ComponentStatic;
let inst = new Component({
methods: {
hello() {
// ...
},
world() {
this.hello;
// ~~~~~
// Error: Property `hello` does not exist on this type.
}
},
});
inst.hello;
// ~~~~~
// Error: Property `hello` does not exist on this type.
In the above example, there should be no errors - however, it appears that no inferences are being drawn as a type argument for Methods, and both this.hello and inst.hello are causing errors.
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par reproduire l’exemple de typage contextuel et d’inférence de constructeur dans l’issue, en vous concentrant sur le type this à l’intérieur de world et sur le type inféré de inst. Suivez les chemins de vérification des types et d’inférence générique de TypeScript qui sont impliqués. C’est terminé lorsque l’exemple ne produit aucune erreur, que this.hello est accepté et que inst.hello est disponible avec un typage approprié.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Bug
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- À l'abandon
- Clarté
- Clairement spécifiée
- Accessibilité débutants
- 25/100