在typescript函数中按条件传递参数
我有如下功能。当在typescript函数中按条件传递参数,typescript,typescript2.0,Typescript,Typescript2.0,我有如下功能。当a==“add”如果a不等于“add”时,我想在p3上设置一些值,只需使用函数中的默认值即可。我怎么做 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 = 'min
a==“add”
如果a
不等于“add”
时,我想在p3上设置一些值,只需使用函数中的默认值即可。我怎么做
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
传递给函数,并使用默认的指定值:
在TypeScript中,我们还可以设置一个值,如果用户不提供参数,或者如果用户在其位置传递未定义的参数,则将为该参数分配该值。这些参数称为默认初始化参数。让我们以上一个示例为例,将姓氏默认为“Smith”
您的示例应该如下所示:
let a = 'add1'
func("a", "b", (a === 'add' ? { p3: 'hallo' } : {}));
func('a','b',(a==“add”)?“x”:未定义)
更多你可以这样做
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 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' } : {}));