打字稿解包重载函数的参数
Typescript unpacking arguments to overloaded function
为了说明我所说的“解包”的意思,请考虑以下示例
function simpleFunc(a: number, b: string): void { /* ... */ }
function simpleProxy(args: [number, string]) {
simpleFunc(...args)
}
这很好用,typescript 将 [number, string] 映射到 (a: number, b: string)。我有一个用例,我必须对具有重载签名的更复杂的函数执行类似的操作,如下所示:
function overloadFunc(name: string): void
function overloadFunc(name: string, content: number): void
function overloadFunc(content: number): void
function overloadFunc(name_or_content: string | number, maybe_content?: number): void {
/* ... */
}
现在无法解包编译。我试过这个:
function overloadProxy1(args: [string] | [string, number] | [number]) {
overloadFunc(...args);
// ^^^^^^^
// Expected 1-2 arguments, but got 0 or more.(2556)
// ... An argument for 'name' was not provided.
}
还有这个:
function overloadProxy2(args: [string | number, number?]) {
overloadFunc(...args);
// ^^^^^^^
// Argument of type 'string | number' is not assignable to parameter of type 'string'.
// Type 'number' is not assignable to type 'string'.(2345)
}
有没有办法让它工作?如果没有,这是否记录在某处?
答案是这个可爱的 Parameters
类型实用程序:
// This way if you want to call it like overloadProxy1(['name'])
function overloadProxy1(args: Parameters<typeof overloadFunc>) {
// ...
}
// Or this way if you want to call it like overloadProxy1('name')
function overloadProxy1(...args: Parameters<typeof overloadFunc>) {
// ...
}
为了说明我所说的“解包”的意思,请考虑以下示例
function simpleFunc(a: number, b: string): void { /* ... */ }
function simpleProxy(args: [number, string]) {
simpleFunc(...args)
}
这很好用,typescript 将 [number, string] 映射到 (a: number, b: string)。我有一个用例,我必须对具有重载签名的更复杂的函数执行类似的操作,如下所示:
function overloadFunc(name: string): void
function overloadFunc(name: string, content: number): void
function overloadFunc(content: number): void
function overloadFunc(name_or_content: string | number, maybe_content?: number): void {
/* ... */
}
现在无法解包编译。我试过这个:
function overloadProxy1(args: [string] | [string, number] | [number]) {
overloadFunc(...args);
// ^^^^^^^
// Expected 1-2 arguments, but got 0 or more.(2556)
// ... An argument for 'name' was not provided.
}
还有这个:
function overloadProxy2(args: [string | number, number?]) {
overloadFunc(...args);
// ^^^^^^^
// Argument of type 'string | number' is not assignable to parameter of type 'string'.
// Type 'number' is not assignable to type 'string'.(2345)
}
有没有办法让它工作?如果没有,这是否记录在某处?
答案是这个可爱的 Parameters
类型实用程序:
// This way if you want to call it like overloadProxy1(['name'])
function overloadProxy1(args: Parameters<typeof overloadFunc>) {
// ...
}
// Or this way if you want to call it like overloadProxy1('name')
function overloadProxy1(...args: Parameters<typeof overloadFunc>) {
// ...
}