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

Union type narrowing with generics not working in TS 3.5 RC strict mode #31456

Closed
ghost opened this issue May 18, 2019 · 2 comments
Closed

Union type narrowing with generics not working in TS 3.5 RC strict mode #31456

ghost opened this issue May 18, 2019 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@ghost
Copy link

ghost commented May 18, 2019

TypeScript Version: 3.5.0-rc / next

Search Terms: 3.5, 3.5 union, 3.5 strict

Code

test.ts:

function fooT<T = string>(bar: T[] | T | undefined) {
  if (bar !== undefined && !Array.isArray(bar))
    throw new Error("expected array")
  else if (bar !== undefined && bar.length === 0) console.log("empty array")
  else console.log("array or undef.")
}

CLI:

npx typescript@3.4.5 --strict true test.ts // compiles
npx typescript@next --strict true test.ts // error

Expected behavior:
Compiles and behaves like ts 3.4.5

Actual behavior:
Error:

test.ts:4:37 - error TS2339: Property 'length' does not exist on type 'T | T[]'.
  Property 'length' does not exist on type 'T'.

Related Issues:
Cannot judge, if it is a duplicate of #31380 .
This is some specific case to base further evaluation on.

@ahejlsberg
Copy link
Member

This is an effect of #30637. Previously, unconstrained type parameters were treated as if they had the constraint {} and therefore could never be null or undefined. That isn't correct because an unconstrained T can be instantiated at any type, including null or undefined. In 3.5 we now check it correctly. That specifically means that bar !== undefined doesn't imply that T disappears from the type in the false branch.

If you explicitly add a constraint to T you get the expected behavior:

function fooT<T extends {} = string>(bar: T[] | T | undefined) {
    // ...
}

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label May 18, 2019
@ghost
Copy link
Author

ghost commented May 18, 2019

thank you for clarification @ahejlsberg, should have read the changelog more carefully.
The new constraint is a bit more verbose, but makes sense to me logically.
Closing the issue!

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

1 participant