microsoft / microsoft/TypeScript
Incorrect widening (constraint fallback?) during inference when union with `undefined` appears in constraint
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.4k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
Bug Report
🔎 Search Terms
union, type inference, imprecise union generic type, generic type.
🕗 Version & Regression Information
This is reproducible on all versions of the playground.
⏯ Playground Link
Playground link with relevant code
💻 Code
export interface Something<
R extends
| {
[K in 'foo' | 'bar' | 'baz']?: {
r?: unknown;
p?: unknown;
};
}
| undefined = undefined
> {}
const o: Something<{ foo: { r: 1; p: 2 }; bar: { r: 3 } }> = {};
declare function something<M extends T extends Something<infer R> ? keyof R : never, T extends Something>(
key: M,
something: T
): M;
declare function somethingBugged<M extends T extends Something<infer R> ? keyof R : never, T extends Something>(
key: M,
something: T
): [M];
const normal = something('foo', o);
// got: "foo"
// expected: "foo"
const bugged = somethingBugged('foo', o);
// got: ["foo" | "bar"]
// expected: ["foo"]
// However with `as const`, the correct type is returned.
const ugly = somethingBugged('foo' as const, o);
// got: ["foo"]
// expected: ["foo"]
🙁 Actual behavior
The type loses its precision and is the union instead of the exact type.
🙂 Expected behavior
The type is exact.
What is strange is that the generic type M loses precision ("foo" -> "foo" | "bar") with the somethingBugged function which returns a tuple of M (and it does the same thing with any other "wrapper", such as an object).
Whereas with the something function there is no problem. Both functions are identical.
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
Comienza con el ejemplo enlazado de TypeScript Playground y compara la inferencia para something y somethingBugged, especialmente cuando el tipo inferido está envuelto en una tupla o un objeto. Investiga por qué M se amplía de "foo" a "foo" | "bar" solo en el tipo de retorno envuelto. Se considerará terminado cuando la forma envuelta conserve el tipo exacto "foo" sin requerir as const.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- typescript
- Área
- compilers
- Tipo de issue
- Error
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 25/100