如何在重载函数上使用参数类型? [重复]

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

此问题已经在这里有了答案:

在TypeScript中,有一个内置的[[Parameters”类型可返回给定函数的参数。它以元组形式返回参数。

这里是一个例子:

declare function foo(a: string, b: number): void; type fooParams = Parameters<typeof foo>; type aType = fooParams[0]; // string type bType = fooParams[1]; // number

但是,如果我们声明一个重载函数,那么我不知道如何为重载函数获取特定Arity的

Parameters

。这是一个例子:declare function foo(a: string, b: number): void; declare function foo(a: boolean, b: string, c: string): void; type fooParams = Parameters<typeof foo>; type aType = fooParams[0]; // boolean type bType = fooParams[1]; // string
看起来函数的最后任何重载声明都将在

Parameters

类型中使用。为了证明这一点,我们可以对函数声明进行重新排序:declare function foo(a: boolean, b: string, c: string): void; declare function foo(a: string, b: number): void; type fooParams = Parameters<typeof foo>; type aType = fooParams[0]; // string type bType = fooParams[1]; // number
所以问题是,我如何为我想要的特定重载函数(例如为2的

foo

函数)提取参数?我问,因为在使用第三方库时,我倾向于使用

Parameters

类型。因此,如果函数被重载,则在尝试为正确的重载函数使用正确的参数类型时,这可能会引起一些问题。重载函数的示例是带有。on()函数的jQuery库。在TypeScript中,有一个内置的Parameters类型,该类型返回给定函数的参数。它以元组形式返回参数。这是一个示例:声明函数foo(a:string,b:number)...
typescript
1个回答
0
投票
看起来已经有人问过这个问题,并且已经确认它不起作用。
© www.soinside.com 2019 - 2024. All rights reserved.