这是一个代码示例,将在运行时失败:
interface IDict {
[key: string]: { id: number; name: string };
}
const something = (unknownKey: string) => {
const aDict: IDict = {};
const a = aDict[unknownKey];
console.log(a.name);
};
字典的正确类型是什么,以便TS强制我们在使用字典时始终执行空检查?
答案 0 :(得分:1)
我建议在编译器选项中使用strictNullCheck标志。 TS在可选对象上看起来将有所不同。当您将| undefined
添加到值定义时,strictNullCheck标志将强制您检查值是否未定义,或者在确定返回类型时使用as { id: number; name: string }
语法映射类型
interface IDict {
[key: string]: { id: number; name: string } | undefined;
}
const something = (unknownKey: string) => {
const aDict: IDict = {};
const a = aDict[unknownKey];
console.log(a.name); // error
if (a !== undefined) {
console.log(a.name); // ok
}
console.log((a as { id: number; name: string }).name); //also ok
};