我想创建一个负责调用其他一些函数的函数.这些其他功能应该会触发类似的业务和清理逻辑.
function foo(arg: number) {
// do something with arg
}
function bar(arg: string) {
// do something with arg
}
const FUNCTIONS = {
foo,
bar,
} as const;
type FnType = keyof typeof FUNCTIONS;
type FnArg<Type extends FnType> = Parameters<typeof FUNCTIONS[Type]>[0];
function callFunction<Type extends FnType>(type: Type, arg: FnArg<Type>) {
// some business logic here that is shared by all functions
const fn = FUNCTIONS[type];
// the type of fn and arg are both derived from Type:
// - 'typeof fn' would be 'typeof Functions[Type]'
// - 'typeof args' would be 'FnArg<Type>'
// However, TS seems to see these 2 types as independent and cannot
// figure out that fn and arg can work together.
return fn(arg); // -> TS doesn't 'know' that arg should have the right type although we know that's the case thanks to generics
}
// generics make sure the second argument is of the right type
callFunction('foo', 5);
callFunction('foo', 'arg'); // errors as expected
callFunction('bar', 'arg');
callFunction('bar', 5); // erros as expected
我能够使用泛型来确保TS判断将被代理到这些函数的参数的类型是否正确.然而,在函数实现中,TS似乎不知道泛型是否会确保参数的类型正确.
你知道有没有办法让TS明白拨打fn(arg)
就可以了?