Skip to content

TS complains about assignability instead of narrowingΒ #61465

Closed as not planned
Closed as not planned
@RedCMD

Description

@RedCMD

πŸ”Ž Search Terms

type narrow

πŸ•— Version & Regression Information

since forever

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.9.0-dev.20250322#code/MYewdgzgLgBANgS2jAvDA2gcgIKYDQyYBC+hAwpgLowCGEMokUA3AFCsBmArmMFAuFoAjYAApgACxoAnAFyFcMAD6ESy8pnWYAIpgCUMAN6sYMBBxijE0AHQJecLgBMAphHFTpeg4ZgB6PxgXaWkQaXoJYJcTUxhpFyguaTA2UwBfdlNzS0kZVDRifSMYNP9AiAkQLjgnIJCwmEj4mJiAmCcQGAgQAFsEiXsAcxgAdwQoCQZPVgygA

πŸ’» Code

const list = ['A', 'B', 'C'] as const;

function abc(char: 'A' | 'B' | 'C' | 'D') {
  if (list.includes(char)) { // errors here
    return;
  }

  if (char == 'B') { } // should error here
  
  // do something with char
}

πŸ™ Actual behavior

TS complains about assignability

Argument of type 'string' is not assignable to parameter of type '"A" | "B" | "C"'.ts(2345)

Image

πŸ™‚ Expected behavior

for TS to recognize that I'm not trying to assign types in the wrong places

and instead to detect that the following comparison appears to be unintentional if (value == 'B') { }

I want it to act like this:
Image

function abc(char: 'A' | 'B' | 'C' | 'D') {
  if (char == 'A' || char == 'B' || char == 'C') {
    return;
  }


  if (char == 'B') { }

  // do something with char
}

Additional information about the issue

I'm trying to add an early exit at the start of the function
and I want the type system to reflect that char will no longer be 'A', 'B', 'C'
but instead it just tries to insult me

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