我有一个字典接口,我希望索引类型为字符串,值为字符串类型。
interface One {
[key: string]: string;
}
如果我将此类型注释为一个包含没有属性的对象的常量变量,那么它不会给我一个错误。
const example: One = {}; // no error why?
上述方法的另一个问题是const example = {} as One;
这也有效。
如果我不提供对象的索引签名,那么它会给我一个错误,即您缺少属性。
interface Two {
first: string;
second: string;
}
const example2: Two: {}; // error missing properties
// to tackle this situation I used type assertion
const example3 = {} as Two; // no error
我的问题是为什么example
变量接受没有属性的对象?
你可能有一个问题,为什么我想要一个没有属性的对象。原因是我想稍后向那个空对象添加一些属性。在那种情况下,我应该做类型断言还是类型注释?