Using Map.get() method in typescript, returns undefined, while I am handling undefined

Issue

I am trying to map the repetition of letters into a hashmap and then returning the first non-repeated character in a string. Following is the function I’ve written to do so:

export const firstNonRepeatedFinder = (aString: string): string | null => {
  const lettersMap: Map<string, number> = new Map<string, number>();

  for (let letter of aString) {
    if (!lettersMap.has(letter)) {
      lettersMap.set(letter, 1);
    } else {
      incrementLetterCount(letter, lettersMap);
    }
  }

  for (let letter of aString) {
    if (lettersMap.get(letter) === 1) return letter;
  }

  return null;

  function incrementLetterCount(
    aLetter: string,
    aLettersHashMap: Map<string, number>
  ): void {
    if (
      aLettersHashMap.has(aLetter) &&
      aLettersHashMap.get(aLetter) !== undefined
    ) {
      aLettersHashMap.set(aLetter, aLettersHashMap.get(aLetter) + 1);
    }
  }
};

However, in incrementLetterCount, function, although I am handling to exclude the undefined values for getting a key in the hashmap, it still complaining about Object is possibly 'undefined' which means that the get method is might return undefined and I cannot proceed with it.

Does anyone know what I am missing here that results in this error?

Solution

I found the following solution to my problem but still not sure why the original code snippet was throwing a compile-time error (although the code was checking against undefined values).

It seems that in Typescript we can assert that the operand is not null/undefined (from here).

A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded.

  function incrementLetterCount(
    aLetter: string,
    aLettersHashMap: Map<string, number>
  ): void {
      aLettersHashMap.set(aLetter, aLettersHashMap.get(aLetter)! + 1);
  }

Answered By – Amirsalar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published