microsoft / microsoft/TypeScript
Optional Generic Type Inference
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 2 d 4 h
- PR fusionados (30 d)
- 132
Descripción
#13487 added default generic types, but it's still not possible to infer a generic type:
type Return<T extends () => S, S = any> = S
Here S takes its default type any, but T could permit inference of a subset type of any for S:
const Hello = () => 'World'
type HelloReturn = Return<typeof Hello> // any
Here HelloReturn still has any type, and TypeScript could infer S as the literal type 'World', which is a subset of any.
Use Case
Here's an example of a fully declarative workaround for #6606, using generic type inference:
type Return<T extends () => S, S = any> = S
const Hello = () => 'World'
type HelloReturn = Return<typeof Hello> // 'World'
Default Type
If return of T is not a subset of S, it should throw an error:
type ReturnString<T extends () => S, S = string> = S
const Hello = () => 'World'
type HelloReturn = ReturnString<typeof Hello> // 'World'
const calculateMeaningOfLife = () => 42
type MeaningOfLife = ReturnString<typeof calculateMeaningOfLife> // ERROR: T should return a subset of String
Multiple Possible Type Inferences
The current implementation always returns the superset (which is just the default generic type), solving this issue would require to return the subset (the most precise type of all the inferred possibilities).
If a type has multiple possible type inferences, TypeScript should check that all these types are not disjoint, and that they all are subsets of the Default Generic Type.
The inferred type is the most precise subset.
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
El issue no menciona archivos, tests ni puntos de entrada. Empieza reproduciendo los ejemplos de inferencia genérica en un entorno de comprobación de tipos de TypeScript y siguiendo el comportamiento existente para los tipos genéricos predeterminados; se considera terminado cuando el tipo inferido es el subconjunto válido más preciso y se rechazan los valores de retorno incompatibles.
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
- 25/100