Typescript: wrong type inference in Promise

Created on 6 May 2019  路  6Comments  路  Source: microsoft/TypeScript


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:

Duplicate

All 6 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kyasbal-1994 picture kyasbal-1994  路  3Comments

dlaberge picture dlaberge  路  3Comments

jbondc picture jbondc  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments