microsoft / microsoft/TypeScript
Union type resolving to one side of the union when spread operator is used
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Go
- Estrellas
- 111k
- Forks
- 14.3k
- Merge medio
- 1 d 19 h
- PR fusionados (30 d)
- 117
Descripción
Bug Report
This issue may be related but they were different enough to warrant a write up here: https://github.com/microsoft/TypeScript/issues/42665
When assigning a union type to a variable, which is immediately instantiated as an object that could possibly be either type at run time, and the spread operator is used to "optionally" apply a property, the type of the variable falls to the type without the extra properties automatically.
🔎 Search Terms
Spread operator, object, union type
🕗 Version & Regression Information
This changed between versions 3.7.5 and 3.8.3.
⏯ Playground Link
Playground link with relevant code
💻 Code
interface Foo {
bar: string;
}
type Bar = Foo & {
baz: string;
}
const produceBoolean = () => Math.random() > 0.5;
const obj: Foo | Bar = {
bar: 'baz',
...(produceBoolean() && {
baz: 'bar'
})
}
if ('baz' in obj) { // obj is "Foo" here
console.log(obj); // obj is "never" here
}
🙁 Actual behavior
Instead of remaining a union type until some discrimination was made, it assumed the object was the side of the union without extra properties.
🙂 Expected behavior
It would remain possibly either or any type in the union until discriminated in the code.
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 la reproducción vinculada en TypeScript Playground y compara su comportamiento entre las versiones indicadas 3.7.5 y 3.8.3. Rastrea el recorrido de comprobación de tipos de object spread hacia una unión y verifica después que el valor resultante siga siendo una unión y que la comprobación 'baz' in obj lo estreche correctamente.
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
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 35/100