microsoft / microsoft/TypeScript
Suggest specifying generic as union if candidates are different
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
TypeScript Version: 2.6.1.
Code
If a generic type can't be formed by picking one of the inference candidates, you'll get the error you posted.
This makes sense, however I would like to question whether we can improve the user experience around this, so errors due to this constraint are easier to understand and fix.
For example:
{
function compare<T>(x: T, y: T): number {
return 1;
}
compare(
'oops',
/* Argument of type '42' is not assignable to parameter of type 'string'. */
42,
);
}
{
function match<T>(cases: { foo: T; bar: T }): T {
return cases.foo;
}
/*
Argument of type '{ foo: number; bar: string; }' is not assignable to parameter of type '{ foo: number; bar: number; }'.
Types of property 'bar' are incompatible.
Type 'string' is not assignable to type 'number'.
*/
match({
foo: 1,
bar: 'foo',
});
}
As a TypeScript user, I have struggled with these errors many times, and I've only recently realised the specific constraint on the type system which is the root cause of these errors: generics are picked from the first candidate and are not widened to include all candidates. I have also seen other people struggle with this when learning TypeScript.
We can fix this error by specifying the generic as a union:
match<string | number>({
foo: 1,
bar: 'foo',
});
However, this fix is really not obvious from the error message, especially if the user is not aware of this constraint on the type system (that generics will not be inferred as unions).
I'm wondering if there's any way we can better surface this constraint to the user, to make it clearer to users how they can fix these type errors, such as by specifying the generic as a union (if that is what they intend).
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
Utilisez les exemples compare et match de l’issue comme reproductions, en vérifiant d’abord leurs diagnostics avec la version actuelle de TypeScript. C’est terminé lorsque le diagnostic explique les différents candidats d’inférence et indique clairement la correction avec un type union explicite lorsque c’est la solution prévue.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- typescript
- Domaine
- compilers
- Type d'issue
- Fonctionnalité
- Difficulté
- 5/5
- Temps estimé
- Plus d'une semaine
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100