How to transform union type to tuple type

后端 未结 2 1795
半阙折子戏
半阙折子戏 2020-11-27 08:42

For example i have type

type abc = \'a\' | \'b\' | \'c\';

How to make tuple type that contains all elements of the union in compile time?

2条回答
  •  一向
    一向 (楼主)
    2020-11-27 09:04

    I've sometimes faced a situation in which I want to derive type B from type A but find that either TS does not support it, or that doing the transformation results in code that's hard to follow. Sometimes, the choice of deriving B from A is arbitrary and I could just as well derive in the other direction. Here if you can start with your tuple, you can easily derive a type that covers all the values that the tuple accepts as elements:

    type X = ["a", "b", "c"];
    
    type AnyElementOf = T[number];
    
    type AnyElementOfX = AnyElementOf;
    

    If you inspect the expansion of AnyElementOfX you'll get "a" | "b" | "c".

提交回复
热议问题