microsoft / microsoft/TypeScript

Union type resolving to one side of the union when spread operator is used

Ouverte
#42,771 2 commentaires 1 réaction 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

Bug Domain: check: Control Flow
Langage dominant
Go
Étoiles
111k
Forks
14.4k
Merge moyen
1 j 19 h
PR mergées (30 j)
117

Description

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.

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Commencez par la reproduction liée dans TypeScript Playground et comparez son comportement entre les versions signalées 3.7.5 et 3.8.3. Suivez le chemin de vérification des types pour object spread dans une union, puis vérifiez que la valeur obtenue reste une union et que le test 'baz' in obj la restreint correctement.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
typescript
Domaine
compilers
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.