只是为了说明“拆包”的含义,请考虑以下示例
function simpleFunc(a: number, b: string): void { /* ... */ }
function simpleProxy(args: [number, string]) {
simpleFunc(...args)
}
这很好用,打字稿将[数字,字符串]映射到(a:数字,b:字符串)。我有一个用例,其中我必须对具有重载签名的更复杂的功能执行类似的操作,例如:
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)
}
有没有办法使这项工作可行?如果没有,这是否记录在某处?
答案 0 :(得分:1)
答案是这个可爱的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>) {
// ...
}