我想在Typescript中创建一个可索引类型的hashmap。这样可以正常工作,但我在执行查找时缺少值undefined
的警告。有没有办法把它变成打字稿?
interface HashMap {
[index: number]: string;
}
const exampleMap: HashMap = {
1: "foo",
2: "bar"
}
const noWarningHere = exampleMap[3];
console.log(noWarningHere.length);
这会在浏览器控制台中提供 TypeError:noWarningHere is undefined ,并且typescript编译器不会抱怨。在其他情况下,编译器会警告它可能是未定义的,我必须先创建一个防护。
答案 0 :(得分:0)
告诉TypeScript HashMap
的属性可以是undefined
:
interface HashMap {
[index: number]: string | undefined;
}
根据您的初步定义,他们不能。事实上,如果在你的例子中你这样做:
exampleMap[4] = undefined;
您收到错误消息称undefined
无法分配给string
;