Typescript: Control flow analysis - object is possibly undefined even when if-check exist

Created on 22 May 2016  路  2Comments  路  Source: microsoft/TypeScript

TypeScript Version:
[email protected]

Code

function foo(ids: any[], bars: { id: any }[], searchId: any) {
    const foundBar = bars.find(bar => bar.id === searchId);
    if (foundBar) {
        const id = ids.find(id => id === foundBar.id);
        //                               ^^^^^^^^ TS2532: Object is possibly 'undefined'.
    }
}

Expected behavior:
Should not given an error because foundBar cannot be undefined because of if (foundBar) check

Actual behavior:
error: TS2532: Object is possibly 'undefined'.

Most helpful comment

and yeah, this is inconvenient that it works only in scope of callback. especially is when you are chaining filter/map/other functions

All 2 comments

ah okay, looks like I forgot that if statement must be in the callback

and yeah, this is inconvenient that it works only in scope of callback. especially is when you are chaining filter/map/other functions

Was this page helpful?
0 / 5 - 0 ratings