-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Type inference and "never" returning function in strict mode #20933
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
// tsc --strictNullCheckts --noEmit test.ts
declare const obj: { prop?: number }
if (!obj.prop) {
}
obj.prop.toFixed(1) // error TS2532: Object is possibly 'undefined'. Edit: Don't think my comment above is relevant, but I won't delete it and leave a dangling reference from the post below. |
@jack-williams that would be expected behaviour, because the last line is reachable code. The issue relates to code that is not reachable. @arusakov is suggesting that CFA should treat a function that returns A better analogue would be: // tsc --strictNullCheckts --noEmit test.ts
declare const obj: { prop?: number }
if (!obj.prop) {
throw Error('Missing property');
}
obj.prop.toFixed(1); // no error, because this is not reachable |
You're correct @kitsonk that I misread. On the actual topic, is it safe to assume that constructing a value of type Am I correct in saything that this example only really applies to top-level code where you can't just write |
I believe As you point out, it can easily be worked around by returning from a function: // tsc --strict --noEmit test.ts
declare const throwError: () => never
declare const obj: { prop?: number }
(() => {
if (!obj.prop) {
return throwError()
}
obj.prop.toFixed(1)
})() |
I understand that |
@kitsonk function throwError() {
throw new Error()
}
declare const obj: { prop?: number }
if (!obj.prop) {
throwError()
}
obj.prop.toFixed(1) // error TS2532: Object is possibly 'undefined'. Example in real life: |
Duplicate of #12825 |
TypeScript Version: 2.7.0-dev.20171229
Code
Expected behavior:
At the last line
obj.prop
is number, not undefinedActual behavior:
At the last line
obj.prop
is possibly undefinedThe text was updated successfully, but these errors were encountered: