Skip to content

Switch inside for loop is converting to intersection #47459

Closed
@apacheli

Description

@apacheli

Bug Report

When using a switch statement inside of a loop, it creates weird intersection issues, which should be union types. This causes issues where types are never, or just not correct in general.

🔎 Search Terms

switch case, loop, union intersection, assigning

🕗 Version & Regression Information

TypeScript 4.5

⏯ Playground Link

playground link

💻 Code

  update(data: Partial<Message>) {
    for (const key in data as Message) {
      switch (key) {
        case "content":
        case "tts": {
          const z = data[key]!;
          let g = this[key]!;
          g = z;
          this[key] = data[key]!;
          break;
        }

z is assignable to g, but data[key] is not assignable to this[key] despite being exactly the same type. key is already narrowed down to the correct keys "content" | "tts".

🙁 Actual behavior

When using intelisense, it seems that type is correctly using |. However, when TRULY assigning to this it seems to have created a union instead (& is not correct).

🙂 Expected behavior

It should stay as a union instead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions