通过正确输入返回具有与其他函数不同签名的函数

问题描述 投票:0回答:1

在我的代码中,我有一个调度函数,它接受一个参数并根据参数返回另一个函数,如下所示:

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'.

有没有办法解决这个问题,或者实现一个更好的没有这个问题的调度函数?

这是游乐场的链接

编辑

我在泛型的帮助下找到了一半的解决方案。现在我可以正确调用调度函数,但我在调度函数中遇到了更多我不理解的错误。

游乐场

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
}
typescript
1个回答
-1
投票

这是我将如何实现它,

type Reason = 'create' | 'delete';

function dispatch(reason: Reason):(args:any)=> any {
    switch(reason) {
        case 'create':
        return createInternal;
        case 'delete':
        return deleteInternal;
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.