我有Maybe
类型的元组:
class Maybe<T>{ }
type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>];
我想将其转换为类型的元组:
type TupleIWant = [string, number, boolean];
所以我尝试了这个:
type ExtractTypes<T> = T extends Maybe<infer MaybeTypes>[] ? MaybeTypes : never;
type TypesArray = ExtractTypes<MaybeTuple>; // string | number | boolean NOT [string, number, boolean]
不起作用的地方:-(
我得到(string | number | boolean)[]
而不是我想要的元组:[string, number, boolean]
我现在想做什么?
答案 0 :(得分:5)
您将需要使用mapped tuple type,它在TypeScript 3.0中不受支持,但在master分支中受支持,并将在TypeScript 3.1中发布。在发布3.1之前,您可以使用TypeScript的未发布版本,或者作为一种变通方法,可以编写条件类型以与元组匹配,只要您认为自己可能拥有,例如like this。>
在TypeScript 3.0中,您可以创建具有正确类型的属性0
,1
和2
的映射类型,如下所示:
class Maybe<T>{}
type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>];
type MaybeType<T> = T extends Maybe<infer MaybeType> ? MaybeType : never;
type MaybeTypes<T> = {[P in keyof T]: MaybeType<T[P]>};
let extractedTypes: MaybeTypes<MaybeTuple> = ["hello", 3, true]
但是,如here所述,它不是真正的元组类型,并且不能分配给真正的元组类型[string, number, boolean]
。