TypeScript Version: 3.4.3
Search Terms:
Code
let foo: string | undefined;
if (!foo) foo = 'hello';
foo.length; // ok
new Promise(resolve => resolve(foo.length));
// ^ should be string, but inferred as string | undefined
Expected behavior:
Actual behavior:
Playground Link:
Related Issues:
No, that is not ok: foo.length -> [Object is possibly 'undefined']
@GongT You mean the 3rd line? There is no error in the playground, with all optional checks enabled.
Most likely, related to #9998.
Yep, see #9998 - we cutoff control flow analysis on function boundaries (mostly), so foo only has it's declared type within the Promise callback. If you capture the narrowed value with a const before the callback is made, that'll capture the narrowed value.
we cutoff control flow analysis on function boundaries (mostly)
Which makes perfect sense, because in general the compiler can't know when a function will be called--or even how many times. In the specific case of Promise we know the function will be called only once, and immediately--but this isn't an assumption the compiler can make in the general case.
let foo: string | undefined;
if (!foo) foo = 'hello';
new Promise(resolve => resolve(foo!.length));
ok,It seems that it is the correct solution