Typescript “error TS2532: Object is possibly 'undefined'” even after undefined check

后端 未结 1 1066
半阙折子戏
半阙折子戏 2020-12-07 00:25

I\'m trying to use the --strict option on tsc but I ran into the following \"weird\" case that I don\'t seem to understand.

If I write:

相关标签:
1条回答
  • 2020-12-07 00:54

    Because the second access to input.query happens inside another function the arrow function passed in to forEach. Flow analysis does not cross function boundaries, so since you are in another function you need to test again.

    An alternative to the double test would be to use a local variable, since the type of the variable is locked in on assignment and it will not include the undefined type :

    function testStrict(input: { query?: { [prop: string]: string } }) {
        if (input.query) {
            const query = input.query;
            Object.keys(input.query).forEach(key => {
                query[key];
            })
        }
        return input;
    }
    
    0 讨论(0)
提交回复
热议问题