microsoft / microsoft/TypeScript

New numeric string type to accurately represent numeric indexes

Abierto
#44,649 16 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Awaiting More Feedback Suggestion
Lenguaje dominante
Go
Estrellas
111k
Forks
14.4k
Merge medio
1 d 19 h
PR fusionados (30 d)
117

Descripción

Suggestion

🔍 Search Terms

Object key type, numeric string type, index signature parameter type

✅ Viability Checklist

My suggestion meets these guidelines:

  • [✅] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [✅] This wouldn't change the runtime behavior of existing JavaScript code
  • [✅] This could be implemented without emitting different JS based on the types of the expressions
  • [✅] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • [✅] This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

A new type should be created to represent numbers in string or number format (a number can be used where this type is used, but the real type is a string representation of a numerical value).

This should be used in cases where object indexes are set to number to allow for number and string representation of said number to be used in indexing and to make it more accurate as the indexes are actually stored as strings even if the restriction is that the creation of a new index should be done with a number.

This will also help with a few other places where the type is indicated as a number, but the real type is a string.

📃 Motivating Example & 💻 Use Cases

Conciseness improvment:

const a: {[prop: number]: number} = {};

a[1] = 123;
// below doesn't currently work even though there is no difference and this means the exact same thing as `a[2] = 321;`
a['2'] = 321; // assuming this worked for the rest of the example below

let i: string = ''; // here to show what the type of `i` is currently
for (i in a) {
    console.log(a, a[i], typeof i);
    // above will outputs { "1": 123, "2": 321 }, 123, "string"
    // in the first iteration, note the difference between the type specified in the object index type (`number`) and the type it really is (`string`)
}

This would instead be something like this (name of type is not final, I'm sure there are better names this can have)

const a: {[prop: numstring]: number} = {};
// since old versions allow `number`, this will be an added possiblity to be more concise
// the type above will make it more obvious that it's a string representation of a number (avoids surprises)

a[1] = 123;
a['2'] = 321; // this would now be allowed as well

let i: numstring = '0'; // here to show what the type of `i` is (type compatible with string, no parsing needed between them)
// can also be `let i: numstring = 0` to auto-wrap numbers
for (i in a) {
    console.log(a, a[i], typeof i);
    // above will outputs: { "1": 123, "2": 321 }, 123, "string"
    // in the first iteration, "string" will be the typeof similarly to how all objects are just "object" with `typeof`

    // this should make it more specific as to what the type is and whether or not the type can be converted to a number

    // the following can also be made to work:
    if (i === '1') {...}
}

This will also be useful in a similar way when looping through an array as the indexes are also treated as strings.

And another benefit outside of this will be to allow for string representation of numbers to be better defined as such in general

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

No se especifica ningún archivo fuente, prueba ni punto de entrada. Empieza revisando el comportamiento propuesto para cadenas numéricas en el issue y los objetivos de diseño de TypeScript enlazados, y después localiza las áreas del compilador que rigen las firmas de índice numéricas y de cadena. Se considera terminado cuando exista un diseño acordado cuyo comportamiento cubra los casos de indexación e iteración mostrados y esté validado mediante pruebas.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
javascript, typescript
Área
compilers
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
25/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.