microsoft / microsoft/TypeScript
Improve support for Symbol.toPrimitive
Personne n'a encore pris cette issue.
- Langage dominant
- Go
- Étoiles
- 111k
- Forks
- 14.3k
- Merge moyen
- 2 j 4 h
- PR mergées (30 j)
- 132
Description
Presently, TS limits index types to 'string', 'number', 'symbol', or 'any'. That's fine, but consider the following:
class Foo {
[Symbol.toPrimitive](): number {
return 1;
}
}
var x = ['a','b','c'];
var f = new Foo();
x[f];
We give the error an index expression argument must be of type ... on the array access.
Foo is for all intents and purposes a wrapper around the number 1 (close to new Number(1)), yet it cannot be used to index an array, since Foo itself is not of type number, string, symbol, or any. We could do extra type-checking to see if an object has a user-defined Symbol.toPrimitive and consider its return types when checking type-coercing operations (after all, if you've opted in to using Symbol.toPrimitve it's probably part of your goal to gain this behavior), such as indexing or mathematics operators.
Building on this, we currently don't support the coercion of Number or String classes to their respective primitive types (which are a specialization of the above issue but which applies to ES5 and ES3 output). Presently one can't do this:
function add(a: string, b: string): number {
var x = new Number(a);
var y = new Number(b);
return x + y;
}
add('10e4', '0x8');
Because since neither x nor y is the 'number' (or 'string') primitive type, the addition operation is not allowed. Though it's still valid js (and without the usage of the Number class, the addition would result in '10e40x8'!).
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 les exemples d’expressions d’index et d’addition dans l’issue, puis suivez les règles de vérification des types pour les arguments d’index et les opérandes arithmétiques. Le travail est terminé lorsque Symbol.toPrimitive et la coercition des wrappers Number/String sont pris en compte de manière cohérente, sans autoriser les opérations invalides.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- javascript, 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