1

文档

虽然字符串索引签名是描述“字典”模式的强大方式,但它们也强制所有属性匹配其返回类型。

然后他们显示这个界面:

interface NumberDictionary {
    [index: string]: number;
    length: number;    // ok, length is a number
    name: string;      // error, the type of 'name' is not a subtype of the indexer
}

我的问题是 - 为什么name必须是索引器的子类型?如果我有一个对象,除了name预期之外的所有东西都是whilenumber怎么办?namestring

然后,文档说:

这是因为字符串索引声明obj.property也可用作obj["property"].

如果nameisstring和 not number,我仍然可以同时使用obj.nameand访问它obj["name"]?我不明白这有什么不同。

4

1 回答 1

2

我不明白这有什么不同。

因为后者obj["name"]至少可能通过索引器属性。一个更好的例子可能是:

declare let s: string;
console.log(obj[s]);

...因为很明显我们使用的是字符串而不是字符串文字"name"。索引器属性允许您这样做,而没有索引器属性,如果您这样做,则会出现错误

interface NumberDictionary {
//    [index: string]: number;       commented out indexer
    length: number;
    name: string;
}

let x: NumberDictionary = {length: 0, name: "foo"};
declare let s: string;
console.log(x[s]);
            ^^^^
            Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'NumberDictionary'.

由于所有属性都可以通过这种方式访问​​,因此它们都必须具有相同的类型。

于 2019-10-01T13:53:31.497 回答