Skip to content

Map#has() should suffice for an undefined check when proceeding Map#get()Β #54930

@SReject

Description

@SReject

Suggestion

πŸ” Search Terms

Map, map has

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

For instances cast as Map<>, a check of Map#has(key) should suffice as an undefined check for the key

πŸ“ƒ Motivating Example

Currently, we are required to have a redundant typecheck after a Map#has() for Map#get() calls:

const myMap : Map<string, string> = new Map();
myMap.set('key', 'value');

if (myMap.has('key')) {

  // ts(2322) - 'string | undefined' is not assignable to type 'string'
  const value : string = myMap.get('key');
}

This suggestion asks that ts infer the type as not a union with undefined if a Map#has() check has proceeded the Map#get() call

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions