2
索引签名被如此定义:打字稿 - 如何打字原稿代表索引签名作为一个通用型
字典
[key: string]: T
阵列
[index: number]: T
这些可以被包裹成一些简单的,可重复使用的类型:
type DictionaryIndex<T> = {
[key: string]: T
}
type ArrayIndex<T> = {
[index: number]: T
}
现在我想把它们包装成一个单一的类型。我尝试这样做:
type Index<TKey extends string|number, TValue> = {
[key: TKey]: TValue
}
这并不编译由于以下错误:
An index signature parameter must be of type 'string' or 'number'.
这是不可能的?
这到底是为了什么?
因为
foo(obj: Index<string, Bar>)
foo(obj: Index<string, Bar> & Fooable<string>)
看起来整洁比
foo(obj: { [key: string]: Bar })
foo(obj: { [key: string]: Bar, canFoo: (foo: string) => Bar })
在TypeScript repo上存在一个问题:https://github.com/Microsoft/TypeScript/issues/13398 猜猜这是不可能的。 –