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

Type predicate can sometimes result in different type than type discrimination #46909

Closed
aslilac opened this issue Nov 23, 2021 · 2 comments Β· Fixed by #49625
Closed

Type predicate can sometimes result in different type than type discrimination #46909

aslilac opened this issue Nov 23, 2021 · 2 comments Β· Fixed by #49625
Labels
Bug A bug in TypeScript Help Wanted You can do this
Milestone

Comments

@aslilac
Copy link

aslilac commented Nov 23, 2021

Bug Report

πŸ”Ž Search Terms

predicate, discrimination

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about 4.5.2. Test in 4.0 and nightly as well.

⏯ Playground Link

Playground link

πŸ’» Code

function test(x: unknown) {
	if (typeof x === "string" || x === 0) {
		x
		if (x === "hello" || x === 0) {
			x
		}
	}

	if (check1(x)) {
		x
		if (check2(x)) {
			x
		}
	}
}

function check1(x: unknown): x is (string | 0) {
	return typeof x === "string" || x === 0;
}

function check2(x: unknown): x is ("hello" | 0) {
	return x === "hello" || x === 0;
}

πŸ™ Actual behavior

In the first set of nested scopes, typeof x is narrowed to string | 0 by the first if, and then "hello" | 0 by the second if. This behavior is correct.
In the second set of nested scopes, typeof x is narrowed to string | 0 by the first if, but is narrowed to 0 by the second if.

πŸ™‚ Expected behavior

"hello" is a valid part of the subset of string, and should be included in the union type. The types derived from these two methods should be identical.

@MartinJohns
Copy link
Contributor

MartinJohns commented Nov 23, 2021

Perhaps related? #31156

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Nov 23, 2021
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Nov 23, 2021
@RyanCavanaugh
Copy link
Member

Behavior dates back to at least 3.3... I'm surprised this hasn't been noticed before (I suppose a union UDTG is weirdish).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Help Wanted You can do this
Projects
None yet
3 participants