TypeScript 映射 : Type 'number | undefined' is not assignable to type 'number'

标签 typescript typeerror

我在 VS Code 中有下面的 typescript 代码,

const hash: Map<string, number> = new Map<string, number>([
    ['Small', 1],
    ['Medium', 2],
    ['Large', 3],
]);
const sz = 'Small';
const num: number = hash.has(sz) ? hash.get(sz) : 0;

它一直在提示:

输入“数字 | undefined' 不可分配给类型'number'。类型“undefined”不可分配给类型“number”。

不确定我在这里做错了什么。 hash.has(sz) 不是已经确保 hash.get(sz) 不会未定义吗?

我当前的方法是使用 const num: number = hash.has(sz) ? hash.get(sz)! : 0;但这对我来说似乎不太优雅。

解决此类问题的正确方法是什么?

最佳答案

const hash: Map<string, number> = new Map<string, number>([
    ['Small', 1],
    ['Medium', 2],
    ['Large', 3],
]);
const sz = 'Small';
const num: number = hash.get(sz) ?? 0;

这应该可以做到。 Map.prototype.get 如果找不到键,则返回 undefined,我们可以将其 null 合并为 0。

关于TypeScript 映射 : Type 'number | undefined' is not assignable to type 'number' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71970946/

相关文章:

javascript - 扩展/装饰 Angular 2 组件和指令

javascript - 类型 Casting json to class angular 2

python - 为什么这个程序从 Aptana IDE 运行而不是在 python 命令中运行?

python - 如何检测数据框对象的语言?

JavaScript 类型错误 : Cannot read property 'id' of undefined

javascript - 无法从导入模块的打字文件中解析 typescript 类,但可以使用绝对路径

typescript - 打字 : SyntaxError: Unexpected token =>

javascript - 你能在 TypeScript 类中设置静态枚举吗?

c - 为什么我收到此格式错误 ‘%c’ 需要类型 ‘int’

javascript - DataTables 无法添加行