Skip to content

tsc misunderstands possible value of variable (TS2367) #48620

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

Closed
smallkirby opened this issue Apr 9, 2022 · 3 comments
Closed

tsc misunderstands possible value of variable (TS2367) #48620

smallkirby opened this issue Apr 9, 2022 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@smallkirby
Copy link

Bug Report

In the below code, tsc emmits the error toward flag = flag === 'B' ? 'B' : 'A';.

type TestType = 'A' | 'B' | 'C';

const f = (strs: string) => {
  let flag: TestType = 'A';
  let other_flag = false;

  for (const line of strs.split('\n')) {
    if (line.length !== 0 && flag === 'B') {
      flag = 'A';
    }

    if (line.startsWith('#')) {
      flag = 'C';
      other_flag = false;
    } else if (line.length !== 0 && other_flag) {
      flag = 'B';
      other_flag = false;
    } else if (line.length !== 0) {
      flag = 'A';
      other_flag = false;
    } else if (line.length === 0) {
      console.log(`flag: ${flag}`);
      flag = flag === 'B' ? 'B' : 'A';
      other_flag = true;
    }

    if (flag === 'C') {
      // DO WORK
    }
  }
};

f(`
# Hello

hello

hello
`);

error message:

index.ts:23:14 - error TS2367: This condition will always return 'false' since the types '"A"' and '"B"' have no overlap.

23       flag = flag === 'B' ? 'B' : 'A';

However, if I set ts-ignore at the line, compile it, and then run it, the condition can actually be true.

$ node ./index.js
flag: A
flag: C
flag: B
flag: B

🔎 Search Terms

This condition will always return

🕗 Version & Regression Information

I tested it by tsc v4.5.5 on local, and tsc nightly on Playground.

⏯ Playground Link

Playground link with relevant code

@smallkirby
Copy link
Author

Oh, it might be duplicate of #46475 , I guess? I'm sorry for my poor search, if it's just same.

@MartinJohns
Copy link
Contributor

It does sound like a duplicate of #46475 to me too.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 11, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

4 participants