此问题已经在这里有了答案:
在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)...