How to 'map' a Tuple to another Tuple type in Typescript 3.0

后端 未结 1 1547
孤城傲影
孤城傲影 2021-01-02 01:07

I have tuple of Maybe types:

class Maybe{ }

type MaybeTuple = [Maybe, Maybe, Maybe];
         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-02 01:58

    You'll need to use a mapped tuple type, which is supported in TypeScript 3.1.

    You can make a mapped type that has properties 0, 1, 2 and length of the correct types, like this:

    class Maybe {}
    
    type MaybeTuple = [Maybe, Maybe, Maybe];
    
    type MaybeType = T extends Maybe ? MaybeType : never;
    type MaybeTypes = {
      [Index in keyof Tuple]: MaybeType;
    } & {length: Tuple['length']};
    
    let extractedTypes: MaybeTypes = ['hello', 3, true];
    

    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.

    0 讨论(0)
提交回复
热议问题