-
Notifications
You must be signed in to change notification settings - Fork 12.8k
TS2.9 narrows {}|undefined
to never after string checks (regression from 2.8)
#25179
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
Comments
The real problem is narrowing So the bug is basically: function stringify(anything: {} | undefined): string {
return typeof anything === "string" ? anything.toUpperCase() : ""; // Property 'toUpperCase' does not exist on type 'never'.
} |
@mhegazy did we want to change our narrowing behavior? function stringify(anything: { toString(): string } | undefined): string {
return typeof anything === "string" ? anything.toUpperCase() : ""; // Property 'toUpperCase' does not exist on type 'never'.
} and expect narrowing to work, but today it will not. |
So what changed since 2.8? |
I haven't looked again, but this code (at least in the longer version
above) compiled in our code base with 2.8, but fails with 2.9.
|
Was |
No, we had strictNullChecks enabled since before 2.7.
|
TypeScript Version: 2.9.2
Search Terms: string never undefined jQuery
Code
Expected behavior:
TypeScript understands that
childSelector
must bestring
in the block. This is what TS 2.8 did.Actual behavior:
TypeScript infers
childSelector
to be never, then outsmarts the user's type annotation ofHTMLElement|null
to be justnull
, then deducts that in the last line, it must be never.Playground Link: http://www.typescriptlang.org/play/#src=declare%20const%20childSelector%3A%20%7B%7D%7Cundefined%3B%0D%0Adeclare%20const%20elem%3A%20HTMLElement%3B%0D%0Aif%20(typeof%20childSelector%20%3D%3D%3D%20'string')%20%7B%0D%0A%20%20%2F%2F%20childSelector%20is%20never%20(bug%3F)%0D%0A%20%20const%20childElement%3A%20HTMLElement%7Cnull%20%3D%20elem.querySelector(childSelector)%3B%0D%0A%20%20%2F%2F%20childElement%20is%20now%20null%0D%0A%20%20if%20(!childElement)%20%7B%0D%0A%20%20%20%20throw%20new%20Error('...')%3B%0D%0A%20%20%7D%0D%0A%20%20%2F%2F%20childElement%20is%20now%20never%0D%0A%20%20childElement.addEventListener('click'%2C%20()%20%3D%3E%201)%3B%0D%0A%7D
The text was updated successfully, but these errors were encountered: