type Whatever = {
name: string;
};
const map: { [key: string]: Whatever } = {};
// Errors
const a: Whatever = {}; // name is required in type Whatever
const b: Whatever = undefined; // undefined not assignable
// No Errors
const c: Whatever = map["not-found"]; // undefined
const d: Whatever = map["not-found"] || {}; // {}
或看看here
我希望c
和d
的分配无法通过类型检查。
如果您的地图包含Whatever?
,则您的代码行为正确。它确实进行类型检查;您只需告诉它map
包含任何key: string
的任何实例。
const map: { [key: string]: Whatever? } = {};
当然,有无限可能的字符串键,因此您无法为它们全部定义一个值,但是您已经以这种方式声明了您的类型,而Typescript不会纠正您。