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

Function returning never in branch doesn't narrow type if it's not explicitly annotated #58170

Closed
nicolo-ribaudo opened this issue Apr 12, 2024 · 3 comments

Comments

@nicolo-ribaudo
Copy link

πŸ”Ž Search Terms

function callback never type narrowing inference

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwxgE8AFWAZxAAowAjALniqlpxg0aoEp4BeAPnioQANxAweA+GgDWqHAHdUXRiJxZgAbgBQ2jEQAOCAIJ94AbwKGQjAETHb8AL479R+ACEzltzfi2PRxddUEhYBDA8cgwhHFBGUwAfTx09YjIYSmZWdj5Bc214IvgWNgwdYvgAeir4AD0Afl1KrEQmeVAAOl8+Xl5-Bx5S9m5UyrgMZBh8DoRyKGxyRCwQchTq2tsAFWt4AHIkzz34YBxV2Jj5xcQiAgALBBAADyNMEGArdz2PPdttJy4ukIpAo1GyZU4kkEwjEEjyFkKxVa7TiIG6uz6-XstiGOQwo2axQmUxmqPgVywSxWaw8OgB2iAA

πŸ’» Code

declare function tryParse(cb: (abort: () => never) => unknown): void;

type A = { type: "A" };
type B = { type: "B" };

declare const node: A | B;

tryParse(abort => {
    abort;
    // ^?

    if (node.type === "A") abort();

    return node satisfies B; // "Type 'A | B' does not satisfy the expected type 'B'"
})

tryParse((abort: () => never) => {
    if (node.type === "A") abort();

    return node satisfies B;
})

πŸ™ Actual behavior

In the first case, node is not refined to B but it still has type A | B

πŸ™‚ Expected behavior

The two usages of tryParse are exactly the same, abort has exactly the same type in both, so they should both narrow the type of node.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

This is working as intended and done for performance reasons. See #51075 and many many others.

@nmain
Copy link

nmain commented Apr 12, 2024

While not precisely a duplicate of #51075, this is related to that and a known limitation of never narrowing. In order for narrowing to work, the type of the variable being called needs to be known before the inference pass happens.

@nicolo-ribaudo
Copy link
Author

Oh thanks πŸ‘

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

3 participants