Вот моя проблема:
function Fn1() {
return 0
}
function Fn2(a: string) {
return a
}
function Fn3(a: number, b: number) {
return a + b
}
const Fns = {
Fn1,
Fn2,
Fn3,
}
function invoke<T extends keyof typeof Fns>(
fnName: T,
...args: Parameters<typeof Fns[T]>
): ReturnType<typeof Fns[T]> {
const fn = Fns[fnName]
if (fn) {
// do something
}
return fn(...args)
}
invoke('Fn1')
invoke('Fn2', 'hello')
invoke('Fn3', 1, 2)
Последние 3 строки указывают на правильные типы, но есть 2 ошибки в инструкции return
внутри тела функции invoke
:
Type 'string | number' is not assignable to type 'ReturnType<{ Fn1: () => number; Fn2: (a: string) => string; Fn3: (a: number, b: number) => number; }[T]>'.
Type 'string' is not assignable to type 'ReturnType<{ Fn1: () => number; Fn2: (a: string) => string; Fn3: (a: number, b: number) => number; }[T]>'. ts(2322)
Expected 2 arguments, but got 0 or more. ts(2556)
Кажется, что TypeScript принимает переменную fn
как тип пересечения, а не тип объединения, как я могу решить эту проблему?