Decompose a TypeScript union type into specific types

前端 未结 1 1357
借酒劲吻你
借酒劲吻你 2021-01-27 13:49

I wonder whether it\'s possible to “split” union types into the specific subtypes in TypeScript. This is the code I tried to use, it should be obvious what I\'m trying to achiev

相关标签:
1条回答
  • For a fixed maximum number of union members, we can extract the union members in a single implementation-defined order by generating an intersection of call signatures and then matching it against a type with multiple call signatures. This version only works with strictFunctionTypes enabled.

    // https://stackoverflow.com/a/50375286
    type UnionToIntersection<U> = 
      (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
    
    type UnionToFunctions<U> =
        U extends unknown ? (k: U) => void : never;
    
    type IntersectionOfFunctionsToType<F> =
        F extends { (a: infer A): void; (b: infer B): void; (c: infer C): void; } ? [A, B, C] :
        F extends { (a: infer A): void; (b: infer B): void; } ? [A, B] :
        F extends { (a: infer A): void } ? [A] :
        never;
    
    type SplitType<T> =
        IntersectionOfFunctionsToType<UnionToIntersection<UnionToFunctions<T>>>;
    
    type Test1 = SplitType<number>;                    // [number]
    type Test2 = SplitType<number | string>;           // [string, number]
    type Test3 = SplitType<number | string | symbol>;  // [string, number, symbol]
    
    0 讨论(0)
提交回复
热议问题