如何在Typescript 3.0中将元组“映射"到另一个元组类型 [英] How to 'map' a Tuple to another Tuple type in Typescript 3.0
问题描述
我有Maybe
类型的元组:
class Maybe<T>{ }
type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>];
我想把它变成一个类型的元组:
and I want to turn this into a tuple of types:
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]
I get (string | number | boolean)[]
rather than the tuple I want: [string, number, boolean]
我现在想做什么?
推荐答案
You'll need to use a mapped tuple type, which is supported in TypeScript 3.1.
您可以创建具有正确类型的属性0
,1
,2
和length
的映射类型,如下所示:
You can make a mapped type that has properties 0
, 1
, 2
and length
of the correct types, like this:
class Maybe<T> {}
type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>];
type MaybeType<T> = T extends Maybe<infer MaybeType> ? MaybeType : never;
type MaybeTypes<Tuple extends [...any[]]> = {
[Index in keyof Tuple]: MaybeType<Tuple[Index]>;
} & {length: Tuple['length']};
let extractedTypes: MaybeTypes<MaybeTuple> = ['hello', 3, true];
如果您使用的是较早版本的Typescript,则可以使用TypeScript的未发布版本,或者作为一种变通方法,可以编写条件类型以与元组匹配,只要您认为自己可能会拥有,例如,像这样.
If you're using an older version of typescript, you can use an unreleased version of TypeScript, or as a workaround, you can write a conditional type to match against tuples as long as you think you are likely to have, e.g., like this.
这篇关于如何在Typescript 3.0中将元组“映射"到另一个元组类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!