在我的代码中,我有一个调度函数,它接受一个参数并根据参数返回另一个函数,类似于这样的:
type Reason = 'create' | 'delete';
function dispatch(reason: Reason) {
switch(reason) {
case 'create':
return createInternal;
case 'delete':
return deleteInternal;
}
}
function createInternal(name: string) {
console.log(name);
}
function deleteInternal(code: number) {
console.log(code);
}
现在这最初有效,因为我返回的函数具有相同的签名.在添加了另一个具有不同签名的函数后,我意识到这有问题."dispatch"函数的返回类型是所有可能返回的函数的联合.
下面的用法现在不再可能,因为类型脚本无法推断返回函数的正确类型.
dispatch('create')('123'); // Argument of type 'string' is not assignable to parameter of type 'never'.
dispatch('delete')(123); // Argument of type 'number' is not assignable to parameter of type 'never'.
有没有方法可以解决这个问题,或者实现一个更好的调度功能而不会出现这个问题?
Edit
在仿制药的帮助下,我找到了一半的解决方案.现在我可以正确调用调度函数,但调度函数内部出现了我不理解的更多错误.
type Reason = 'create' | 'delete';
type DispatchedFunction<T extends Reason> = T extends 'create' ? typeof createInternal : typeof deleteInternal;
function dispatch<R extends Reason>(reason: R): DispatchedFunction<R> {
switch(reason) {
case 'create':
// Type '(name: string) => void' is not assignable to type 'DispatchedFunction<R>'.
return createInternal;
case 'delete':
// Type '(code: number) => void' is not assignable to type 'DispatchedFunction<R>'.
return deleteInternal;
}
return () => {} // I had to add this so the function doesn't return undefined
}