首页 > 解决方案 > 跳过 TypeScript 函数中的参数

问题描述

我已经从问题Skip arguments in a JavaScript function中尝试了Pacerier 的答案。但它似乎不起作用。

我有一个有很多参数的函数

this.service.list("all",null, null, localStorage.getItem('currentProgram'), null, 100, ...Array(2), environment.liveMode).subscribe(...)

我发现的唯一方法是一一编写,例如(,null,null或undefined,undefined)。

我还设置了一个测试方法,看看有没有不同,但效果不好。

test(a: any, b: any, c: any, d: string) {
    console.log(d)
}

ngOnInit() {
    this.test(...Array(3), "a")
}

我还尝试了答案中提出的其他语法。

在 TypeScript 中是否有更简洁的方法来执行此操作?

标签: angulartypescriptfunctionargumentsspread

解决方案


在 TypeScript 中,如果你想跳过一个参数,你必须明确地传递undefinednull作为参数值。例子:

function f(param1?: string, param2?: number, param3?: boolean) {
// do something
}

f(,,true); // ❌ Error
f(...[,,], true); // ❌ Error
f(...Array(2), true); // ❌ Error
f(undefined, undefined, true); // ✅ Works 
f(null, null, true); // ✅ Works

您可以在 TypeScript 文档的此部分中找到更多信息和示例:https ://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters


推荐阅读