Search code examples
typescript

How to define a function type which return the type corresponding the input param in typescript


type A = {
  aa: string;
  bb: number;
};

type G = {
  <T extends keyof A>(a: T): A[T];
  <T1 extends keyof A, T2 extends keyof A>(a: T1, b: T2): [A[T1], A[T2]];
  // ...
};

const g = {} as G;
const x = g('aa'); //string
const y = g('bb', 'aa'); //[number, string]
const z = g('bb', 'aa', 'cc'); //Expected 1-2 arguments, but got 3

What should I do if I want to pass infinite number of params and get the corresponding type?


Solution

  • You can do that with variadic tuple types and rest parameters.

    type A = {
      aa: string;
      bb: number;
    };
    
    type G = {
      <T extends (keyof A)[]>(...keys: T): { [K in keyof T]: A[T[K]] };
    };
    
    declare const g: G; 
    const x = g("aa"); // [string]
    const y = g("bb", "aa"); // [number, string]
    const z = g("bb", "aa", "cc");
    //                      ~~~~
    // Argument of type '"cc"' is not assignable to parameter of type 'keyof A'
    

    TypeScript Playground