Skip to content

Bug: Predicate function does not narrow correctly #61652

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
mozesstumpf opened this issue May 4, 2025 · 2 comments
Closed

Bug: Predicate function does not narrow correctly #61652

mozesstumpf opened this issue May 4, 2025 · 2 comments

Comments

@mozesstumpf
Copy link

πŸ”Ž Search Terms

predicate

πŸ•— Version & Regression Information

It worked till version version 5.4.5

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.3#code/JYOwLgpgTgZghgYwgAgILIN4FgBQBIMATwAcIAuZAIjkoG5cBfXXUSWRFAIU1wJPKoAjOo2Y5W0eEmQBhHviKkKlBCJxMcLcJI7IAIvL5KqAEzUbcilKm4BeNMgA+yTvU04rsg-bnO9by340ABtg5HsbJy8AnAQAexAAZzBkOEEKSPsAWTgwAAsAOig4EBM4gFsACgBKZAA+ZAAGAoBWZAB+TGQrZRpkBmQKDG7+ZWF+mPiklLhQjNDw1MFJhOTkYESZb2RK2eD54NrbBux8KAgwAFcoEFTQgs9bJ6pVJ2c9h6Cn+0ozNwYYsAYDsNltdqFqrVTng9rRkAB6eFoBBXWYUEAQABu0AANMgAKIAD1IKIgJgoW1EOCAA

πŸ’» Code

interface A {
	type: "a";
}

interface B {
	type: "b";
}

interface C {
	type: "c";
}

interface D {
	type: "d";
}

type AB = A | B;

type CD = C | D;

type All = AB | CD;

const ab: AB = Math.random() > 0.5 ? { type: "a" } : { type: "b" };

const all: All = ab;

const isCD = (all: All) => {
	return all.type === "c" || all.type === "d";
};

if (isCD(all)) {
	all; // Actual: never, Expected: CD
}

πŸ™ Actual behavior

all's type is never inside the if statement

πŸ™‚ Expected behavior

all's type should be CD inside the if statement

Additional information about the issue

When we initialize the all, we explicitly give it the type All (even tho we assign an AB to it), and when we hover on it, it shows that its type is All.
But, when we check it with the predicate function (isCD), it looks like that it tries to compare the AB type instead of the All, and its result will be never since AB and CD has no overlap.

@MartinJohns
Copy link
Contributor

This is working as intended. Assignment narrows, the compiler can see that all can possibly only be A or B, so after checking both with your predicate the resulting type is never.

You can avoid the narrowing upon assignment using a type assertion: const all: All = ab as All;

@mozesstumpf
Copy link
Author

Yep, your right. The error on my code is actually caused because the assignment itself that does not narrowed correctly inside the while loop, but that's another bug, so it can be closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants