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

Generic conditional type narrowing doesn't cascade as expected #46975

Open
milohansen opened this issue Dec 1, 2021 · 2 comments
Open

Generic conditional type narrowing doesn't cascade as expected #46975

milohansen opened this issue Dec 1, 2021 · 2 comments
Labels
Bug A bug in TypeScript
Milestone

Comments

@milohansen
Copy link

Bug Report

I've tried my best to search for related issues and read the documentation thoroughly but failed to find any useful information. I'm sorry if this bug turns out to be duplicate or even not a bug at all.

🔎 Search Terms

conditional type if undefined

🕗 Version & Regression Information

All versions available in the playground (http://www.typescriptlang.org/play)

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about Generics and Type Guards.

⏯ Playground Link

Playground link

💻 Code

type Foo<T extends number | string> = {
  value: T;
}

type Narrow<T extends number | string | undefined> = T extends undefined ? never : Foo<T>;
//                                                                                     ^
// ERROR: Type 'string | number | undefined' is not assignable to type 'string | number'.

🙁 Actual behavior

In the above example, T throws an error when passed to Foo because the compiler believes T could be undefined.

🙂 Expected behavior

The condition has checked if T extends undefined so I would expect T's type to be narrowed from string | number | undefined to string | number on the right side of the ternary operator.

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

I feel like there might be a theoretical justification for why we don't do this, but I can't reconstruct it at the moment

@jack-williams
Copy link
Collaborator

This is related, but I'm not sure if it is out-of-date: #29188 (comment)

FWIW, this works

type Narrow<T extends number | string | undefined> = T extends number | string  ? Foo<T> : never;

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

No branches or pull requests

3 participants