TypeScript reporting Object is possibly 'undefined' when it shouldn't

前端 未结 3 2081
面向向阳花
面向向阳花 2021-01-20 16:53

I\'m trying to understand why TypeScript is giving me the following error: Object is possibly \'undefined\'

Here\'s the code snippet:



        
3条回答
  •  爱一瞬间的悲伤
    2021-01-20 17:35

    There is no type guarding for Map.has() See this issue or this issue.

    You can fix the issue by having a fallback of 0, -1 or whatever you think would be best for your code.

    const mergedDepsObj: { [key: string]: string } = {}
    const results: Map = new Map();
    Object.keys(mergedDepsObj).forEach((key: string) => {
      results.has(key) ? results.set(key, (results.get(key) || 0) + 1) : results.set(key, 0);
    })
    

    Custom Type Guard

    However, above being said, we make our own type guard with help from this comment.

    interface Map {
        // Works if there are other known strings.
        has(this: MapWith, key: CheckedString): this is MapWith
    
        has(this: Map, key: CheckedString): this is MapWith
    }
    
    interface MapWith extends Map {
        get(k: DefiniteKey): V;
    }
    
    const mergedDepsObj: { [key: string]: string } = {}
    const results: Map = new Map();
    
    Object.keys(mergedDepsObj).forEach((key: string) => {
        results.has(key) ? results.set(key, results.get(key) + 1) : results.set(key, 0);
    })
    

    We can see it in action here

提交回复
热议问题