microsoft / microsoft/TypeScript

Support type inference for Symbol keys on function

Abierto
#61,214 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Domain: check: Type Inference Help Wanted Possible Improvement
Lenguaje dominante
Go
Estrellas
111k
Forks
14.3k
Merge medio
2 d 4 h
PR fusionados (30 d)
132

Descripción

### 🔍 Search Terms

symbol index closure function ts7022

### ✅ Viability Checklist

- [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code
- [x] This wouldn't change the runtime behavior of existing JavaScript code
- [x] This could be implemented without emitting different JS based on the types of the expressions
- [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- [x] This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- [x] This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals

### ⭐ Suggestion

Typescript doesn't correctly infer the type when using a symbol as the key when adding a property to a function type.

Here is an example:

```
const TestSymbol: unique symbol = Symbol();

const c = () => {
return 'Hello, world!';
};
c['testProp'] = ['Hello']; // String property is correctly inferred to be of the type string[]
c[TestSymbol] = ['Hello']; // Typescript complains about the type being implicitly any.

c[TestSymbol] = ['Hello'] as string[] // This works as a workaround for this limitation in typescript.
```

The full error from the language server:

```
c[TestSymbol] implicitly has type 'any' because it does not have a type annotation
and is referenced directly or indirectly in its own initializer. (tsserver 7022)
```

Using a symbol this way works without any issues in plain javascript. I've tested Firefox, Chromium, Node and Bun and all these runtimes handle using symbols as property keys on a function without any issue.

It is very limiting not being able to use symbols naturally in typescript the same way they work in javascript. It would be great if typescript could infer the type of the property when using a symbol as the key the same way it does when using a string for the key.

### 📃 Motivating Example

I've not written any blog posts about this.

### 💻 Use Cases

1. What do you want to use this for? I'm building some infrastructure code where I want to append some information to various objects. Using symbols removes the risk of key collisions that can occur when using strings.
3. What shortcomings exist with current approaches? Using strings instead of symbols or manually casting to the expected type can lead to unexpected collisions and type errors.
4. What workarounds are you using in the meantime? Strings and manually casting to the expected type.

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

Comienza reproduciendo el ejemplo de propiedad de función y su diagnóstico 7022 de tsserver. No se especifica ningún archivo de código fuente ni ninguna prueba, así que sigue el tratamiento que hace el compilador de las propiedades de símbolo calculadas y de los casos de inferencia relacionados. Se considera terminado cuando la asignación con clave de símbolo infiere su tipo de propiedad sin una anotación explícita, mientras el comportamiento existente para claves de cadena permanece sin cambios.

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

Evaluación

Stack tecnológico
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
42/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.