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

Unable to narrow parameterized generic types for functions #25039

Closed
lingz opened this issue Jun 18, 2018 · 4 comments
Closed

Unable to narrow parameterized generic types for functions #25039

lingz opened this issue Jun 18, 2018 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@lingz
Copy link

lingz commented Jun 18, 2018

TypeScript Version: 2.8

Code

function test<T extends 'a' | 'b'>(x: T) {
  if (x === 'a') {
    const z1 = x;
  }
}

function test2(x: 'a' | 'b') {
  if (x === 'a') {
    const z2 = x;
  }
}

Expected behavior:
z1 and z2 should have the same type, which is a

Actual behavior:
function test is unable to narrow parameter x, with the if check, and z2 resolves to x

@lingz lingz changed the title Unable to narrow generic types for functions Unable to narrow parameterized generic types for functions Jun 18, 2018
@MartinJohns
Copy link
Contributor

With strictNullChecks enabled your code won't even compile, because the type null is not compatible with the type 'a' | 'b'.

Without strictNullChecks the value null is implicitly compatible with every type. When you call test(null) the compiler resolves to any because it can't figure out the type of T. Based on null the compiler can't deduct any sensible type. You could expect that it should return 'a' | 'b', because T must extend from it, but that would still only be a "guess". There's no T-type known.

@lingz
Copy link
Author

lingz commented Jun 18, 2018

I think I communicated the issue confusingly, it was not about the actual return type but the type guard in the implementation, I edited the first post to reflect that.

@mhegazy
Copy link
Contributor

mhegazy commented Jun 19, 2018

Duplicate of #13995

@mhegazy mhegazy marked this as a duplicate of #13995 Jun 19, 2018
@mhegazy mhegazy added the Duplicate An existing issue was already created label Jun 19, 2018
@typescript-bot
Copy link
Collaborator

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

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