首页 > 解决方案 > 如何正确键入调用另一个函数并传递可变数量参数的函数

问题描述

这就是这种情况。在我的应用程序中,我想创建一个通用函数,允许我重用一些通用逻辑。

我想保留这样的配置文件:

const configs = {
    getSomething: {
        transformer: (): SomeType => ({ some: 'type' }),
        getUrl: () => '/some/path'
    },
    deleteSomething: {
        transformer: (): SomeOtherType => ({ other: 'sometype' }),
        getUrl: (id: string) => `/some/${id}other/path`
    }
}

然后,在可重用函数(如下)中,我无法正确键入getUrl调用。这是在普通 JS 中的样子:

export function doSomethingGeneric(accessor, params) {
    const config = configs[accessor]

    return config.getUrl(...params)
}

为了这个问题,这是一个精简的版本。我能够成功键入泛型函数以返回SomeTypeSomeOtherType基于accessor. 我以为我可以对 使用相同的概念getUrl,但这不起作用:

type Configs = typeof configs
type Keys = keyof Configs
export function doSomethingGeneric<
    A extends Keys,
    Params extends Parameters<Configs[A]['getUrl']>
>(accessor: A, params: Params) {
    const config = configs[accessor]

    return config.getUrl(...params)
}

我在 return 语句中收到错误(...params)消息,并显示以下消息:

Expected 1 arguments, but got 0 or more.

各位大佬怎么解决这个问题?任何帮助是极大的赞赏!

标签: typescripttypescript-typings

解决方案


推荐阅读