Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking β€œSign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TS complains about assignability instead of narrowing #61465

Open
RedCMD opened this issue Mar 22, 2025 Β· 1 comment
Open

TS complains about assignability instead of narrowing #61465

RedCMD opened this issue Mar 22, 2025 Β· 1 comment
Labels
Duplicate An existing issue was already created

Comments

@RedCMD
Copy link

RedCMD commented Mar 22, 2025 β€’

πŸ”Ž 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

@MartinJohns
Copy link
Contributor

MartinJohns commented Mar 22, 2025 β€’

Duplicate of #60073 and many many more.

instead it just tries to insult me

It's not trying to insult you, it's informing you of an error. Don't take compiler errors personally.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants