1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22import assert from 'node:assert'; const functions = { add: (a: number, b: number) => a + b, pow: (a: number) => a * a, twice: (a: string) => a + a, } as const; type FunctionId = keyof typeof functions; type GetFunction<T extends FunctionId> = typeof functions[T]; function runFunction<Id extends FunctionId>( id: Id, ...parameters: Parameters<GetFunction<Id>> ): ReturnType<GetFunction<Id>> { const f = functions[id]; return f(...parameters); } assert(runFunction('add', 1, 2) === 3); assert(runFunction('pow', 6) === 36); assert(runFunction('twice', 'hello ') === 'hello hello ');

runFunction은 정해진 함수 키랑 인자로 또 다른 함수를 호출하는 함수임.

함수 호출은 타입 문제가 없는데 f(...parameters) 이부분에서 문제가 있음

f의 타입이 유니언 타입으로 추론돼서 그런거같음

이런 함수를 만들 방법이 있을까 any 이런거 안쓰고


오류는 아래처럼 나옴

Type 'string | number' is not assignable to type 'ReturnType<GetFunction<Id>>'.
Type 'string' is not assignable to type 'ReturnType<GetFunction<Id>>'.
ts(2322)
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)