简体   繁体   English

在 typescript 中使用 Map.get() 方法,返回 undefined,而我正在处理 undefined

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

I am trying to map the repetition of letters into a hashmap and then returning the first non-repeated character in a string.我正在尝试将 map 字母的重复转换为 hashmap,然后返回字符串中的第一个非重复字符。 Following is the function I've written to do so:以下是我为此编写的 function:

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.然而,在incrementLetterCount中,function,虽然我正在处理排除undefined的值以获取 hashmap 中的key ,但它仍然抱怨Object is possibly 'undefined' ,这意味着get方法可能返回未定义,我无法继续它.

Does anyone know what I am missing here that results in this error?有谁知道我在这里遗漏了什么导致了这个错误?

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).我找到了以下问题的解决方案,但仍然不确定为什么原始代码片段会引发编译时错误(尽管代码正在检查undefined的值)。

It seems that in Typescript we can assert that the operand is not null/undefined (from here ).似乎在 Typescript 中,我们可以断言操作数不是null/undefined (从这里)。

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.具体来说,操作 x。 produces a value of the type of x with null and undefined excluded.生成 x 类型的值,其中 null 和未定义的除外。

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

Another reason is the tsconfig.json might have the following settings另一个原因是 tsconfig.json 可能有以下设置

"strict": true, /* Enable all strict type-checking options. "strict": true, /* 启用所有严格类型检查选项。 */ */

if you take out the line, the error should go away.如果你取出那行,错误应该是go。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM