【发布时间】:2017-02-10 09:25:32
【问题描述】:
TypeScript 中的索引签名是这样定义的:
字典
[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
}
由于以下错误,无法编译:
索引签名参数必须是“字符串”或“数字”类型。
这不可能吗?
到底是为了什么?
因为
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 上有一个关于此的问题:github.com/Microsoft/TypeScript/issues/13398 Guess it is not possible.
标签: generics typescript generic-constraints