Variadic generic types in TypeScript?

前端 未结 1 656
广开言路
广开言路 2021-01-06 06:30

I\'d like to make a function in TypeScript that takes an array of constructor functions and returns a corresponding array of instances. See code below.

Note that th

相关标签:
1条回答
  • 2021-01-06 07:03

    You can do this in TS3.1 and above using mapped array/tuple types. It's easier to get tuples inferred for rest parameters than it is for array parameters, so I'll show that instead:

    function getVariadic<T extends Array<AnyCon>>(...cons: T): {
      [K in keyof T]: T[K] extends AnyCon ? InstanceType<T[K]> : never
    };
    function getVariadic(...cons: AnyCon[]): any[] {
      return cons.map((c: AnyCon) => new c());
    }
    
    let [t2, t3]: [T2, T3] = getVariadic(T2, T3);
    

    This behaves as you expect, I think. Hope that helps. Good luck!


    EDIT: if you really need to do it with an array it's easy to type the function but a little harder to call it in such a way that the order of the array is preserved as a tuple:

    function getArray<T extends Array<AnyCon>>(cons: T): {
      [K in keyof T]: T[K] extends AnyCon ? InstanceType<T[K]> : never
    };
    function getArray(cons: AnyCon[]): any[] {
      return cons.map((c: AnyCon) => new c());
    }
    
    // error, getArray([T2, T3]) returns (T2 | T3)[]!
    let [t2, t3]: [T2, T3] = getArray([T2, T3]); //                                                                     
    0 讨论(0)
提交回复
热议问题