[英]pass parameter by condition in typescript function
我有 function,如下所示。 当a === "add"
如果a
不等于"add"
时,我想在 p3 上设置一些值,只需使用 function 中的默认值。我该怎么做?
function func(p1: string, p2: string, p3: string = 'value'): void{
console.log(p1);
console.log(p2);
console.log(p3);
};
let a = 'add';
func('a', 'b'); // output: a, b, x
let a = 'mins';
func('a', 'b'); // output: a, b, value
// something like
func('a', 'b', (a === "add")? "x") // output: a, b, value
根据文档,您可以将undefined
传递给 function,您将使用默认的指定值:
在 TypeScript 中,我们还可以设置一个值,如果用户没有提供一个参数,或者如果用户在其位置传递 undefined ,则将分配一个参数。 这些称为默认初始化参数。 让我们以前面的例子为例,并将姓氏默认为“Smith”。
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined); // still works, also returns "Bob Smith"
你的例子应该是这样的:
func('a', 'b', (a === "add")? "x": undefined)
更多在这里
你可以这样做。
func('a', 'b', ((a === "add") ? "x" : undefined));
但我更喜欢这个。
if (a === 'add') func('a', 'b', 'x');
else func('a', 'b')
在最后一行,这样做:
func('a', 'b', (a === "add") ? "x" : undefined) // output: a, b, value
但这不是人们喜欢在生产代码或代码审查中看到的设计。 最好将其包装在一些 if/else 中,以便其他人了解发生了什么:
if (a === 'add'){
func('a', 'b','x');
} else {
func('a', 'b');
}
您可以将 function 重写为:
function func(p1: string, p2: string, { p3 = 'value' }): void{
console.log(p1);
console.log(p2);
console.log(p3);
};
然后你可以这样称呼它:
let a = 'add1'
func("a", "b", (a === 'add' ? { p3: 'hallo' } : {}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.