简体   繁体   English

按条件传参 typescript function

[英]pass parameter by condition in typescript function

I have function like following.我有 function,如下所示。 I want to set some value on p3 when a === "add" if a is not equal to "add" just use the default value from function. how can i do it?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

According to the documentation, you can pass undefined to the function and you will use the default specified value:根据文档,您可以将undefined传递给 function,您将使用默认的指定值:

In TypeScript, we can also set a value that a parameter will be assigned if the user does not provide one, or if the user passes undefined in its place.在 TypeScript 中,我们还可以设置一个值,如果用户没有提供一个参数,或者如果用户在其位置传递 undefined ,则将分配一个参数。 These are called default-initialized parameters.这些称为默认初始化参数。 Let's take the previous example and default the last name to "Smith".让我们以前面的例子为例,并将姓氏默认为“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"

your example should look like this:你的例子应该是这样的:

func('a', 'b', (a === "add")? "x": undefined)

More here更多在这里

You can do it like this.你可以这样做。

func('a', 'b', ((a === "add") ? "x" : undefined));

But i would prefer this instead.但我更喜欢这个。

if (a === 'add') func('a', 'b', 'x');
else func('a', 'b')

In the last line, do this:在最后一行,这样做:

func('a', 'b', (a === "add") ? "x" : undefined) // output: a, b, value

But this is not a design that one likes to see in production code or in a code review.但这不是人们喜欢在生产代码或代码审查中看到的设计。 Better wrap it in some if/else like so, so that others understand what's going on:最好将其包装在一些 if/else 中,以便其他人了解发生了什么:

if (a === 'add'){
  func('a', 'b','x');
} else {
  func('a', 'b');
}

you could rewrite your function a little bit to:您可以将 function 重写为:

function func(p1: string, p2: string, { p3 = 'value' }): void{
  console.log(p1);
  console.log(p2);
  console.log(p3);
};

then you can call it like this:然后你可以这样称呼它:

let a = 'add1'

func("a", "b", (a === 'add' ? { p3: 'hallo' } : {}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM