【发布时间】:2019-08-15 12:30:42
【问题描述】:
我有一个泛型类,其中类型参数是一个元组。我无法在具有限制为元组索引的参数的类上创建方法。
例如(playground link):
class FormArray<T extends [any, ...any[]]> {
constructor(public value: T) {}
// how to restrict `I` to only valid index numbers of `T` ?
get<I extends keyof T>(index: I): T[I] {
return this.value[index];
}
}
我知道你可以做的是使用keyof 获取元组上的所有属性,其中将包括与元组包含的对象关联的键(即“0”、“1”等)。不幸的是,keyof 在元组中引入了 所有 属性,包括“长度”、“拼接”等。
我尝试使用keyof 并排除所有不属于number 类型的属性,但后来我意识到keyof 将索引属性(“0”、“1”等)作为类型返回string.
目前是否可以在 Typescript 中完成此操作?谢谢!
更新
要添加到下面接受的答案,以下是一种解决方法
type ArrayKeys = keyof any[];
type StringIndices<T> = Exclude<keyof T, ArrayKeys>;
interface IndexMap {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"11": 11,
"12": 12,
}
type CastToNumber<T> = T extends keyof IndexMap ? IndexMap[T] : number;
type Indices<T> = CastToNumber<StringIndices<T>>;
class FormArray<T extends [any, ...any[]]> {
constructor(public value: T) {}
get<I extends Indices<T>>(index: I): T[I] {
return this.value[index];
}
}
这里,如果元组的长度不超过 13,我们可以成功提取元组的属性索引号。否则,我们返回通用索引number。
【问题讨论】:
标签: typescript typescript-generics