1

I wanna infer interface's property type from generic key

For example:

interface Api {
  foo: (p: string) => number;
  bar: (p: number) => string;
  baz: () => number[];
}

Just call api from key. But this not worked

const api: Api;

function callApi<K extends keyof Api>(apiName: K, ...params: Parameters<Api[K]>) {
  // Expected 1 arguments, but got 0 or more.
  // An argument for 'p' was not provided.
  // actually, params is [string] | [number] | [], should be matched
  api[apiName](...params);

  // How to fix this?
  // when apiName is 'foo', params must be `[string]`
  // when apiName is 'bar', params must be `[number]`
  // when apiName is 'foo', params must be `[]`
}

But this works

callApi('foo', 1); // Argument of type 'number' is not assignable to parameter of type 'string'.
callApi('bar', '1'); // Argument of type 'string' is not assignable to parameter of type 'number'
niminjie
  • 11
  • 1
  • 2

0 Answers0