TypeScript 接口数组类型错误 TS2411

8

我很难理解这个问题:

There are two types of supported index types: string and number. It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type. In this example, the property does not match the more general index, and the type-checker gives an error:

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

来源:TypeScript Handbook中的接口

我尝试了4种情况,但仍然不明白发生了什么。有人能解释一下为什么只有[index: string]: string;会出现错误TS2411吗? 这里是图片描述

另一个例子:

另一个例子


你错过了一个 codio@compact-guide。我不认为有任何理由隐藏它。 - basarat
错过两个正好..... - user1482015
不错。隐藏它让我想要了解更多 :) - basarat
3个回答

5
如果你有 [index: string]: string;,那么所有的属性必须是 string 类型。因此:
interface Dictionary {
    [index: string]: string;
    length: number;    // error, length is not a string.
}

谢谢,很抱歉回复晚了。我太愚蠢了。我在你的答案中加入了一个测试用例,你能帮我吗? - user1482015
抱歉,我不清楚你对哪个代码示例有疑问。 - basarat
抱歉,我刚刚添加了它。 - user1482015
如果您在游乐场中尝试,那种情况也是一个错误。我想您可能使用的是较旧版本的tsc。 - basarat
只有当我添加一行时,它才会出错 --> var foo:Dictionary = ['peter', 'john']; <-- 这是你的意思吗 ^_^ - user1482015
抱歉,我重新整理了我的问题。我认为我的测试用例出了问题,请忽略我之前的评论。 - user1482015

2
一种使用TypeScript 2.4的解决方法是:
interface Dictionary {
    [index: string]: string | number;
    length: number;
}

然而,当使用时,您可能需要显式转换

let v = dict.key as string

0
可以支持两种类型的索引,但是有一个限制,即从数字索引返回的类型必须是从字符串索引返回的类型的子类型。
此外,没有疑问,答案是否定的。这个数组无论如何都不会起作用:
interface Dictionary {
    [index: string]: string;
    length: number;  // error
}

因为即使这样也能工作:

interface Dictionary {
    [index: string]: string;
}

var dic: Dictionary = {}
dic[1] = "123"

请注意,我们正在使用数字索引字符串数组。
"interface Dictionary { [index: string]: MYCLASS; }" 旨在支持您定义允许的值,但不是索引的类型,抱歉。
你所做的不是关于接口,而是关于数组:http://www.typescriptlang.org/Handbook#interfaces-array-types

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接