这是一个在运行时失败的代码示例:
interface IDict {
[key: string]: { id: number; name: string };
}
const something = (unknownKey: string) => {
const aDict: IDict = {};
const a = aDict[unknownKey];
console.log(a.name);
};
字典的正确类型是什么,以便TS强制我们在使用它时总是进行空检查?
我建议在编译器选项中使用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
};