简体   繁体   English

如何在 Typescript 中使用默认值定义可选的构造函数参数

[英]How to define optional constructor arguments with defaults in Typescript

Is it possible to have optional constructor arguments with default value, like this是否可以使用具有默认值的可选构造函数参数,像这样

export class Test {
    constructor(private foo?: string="foo", private bar?: string="bar") {}
}

This gives me the following error:这给了我以下错误:

Parameter cannot have question mark and initializer.参数不能有问号和初始值设定项。

I would like to create instances like我想创建这样的实例

x = new Test();               // x.foo === 'foo'            
x = new Test('foo1');         // x.foo === 'foo1'
x = new Test('foo1', 'bar1');

What is the correct typescript way to achieve this?实现这一目标的正确打字稿方法是什么?

An argument which has a default value is optional by definition, as stated in the docs :具有默认值的参数根据定义是可选的,如文档中所述

Default-initialized parameters that come after all required parameters are treated as optional, and just like optional parameters, can be omitted when calling their respective function在所有必需参数之后的默认初始化参数被视为可选参数,就像可选参数一样,在调用它们各自的函数时可以省略

It's the same for constructors as it is for other functions, so in your case:构造函数和其他函数一样,所以在你的情况下:

export class Test {
    constructor(private foo: string = "foo", private bar: string = "bar") {}
}

You can add question mark after your args, which is cleaner.您可以在 args 后添加问号,这样更简洁。 If you add default parameters, it should be optional by default.如果添加默认参数,默认情况下应该是可选的。

export class Test {
   foo: string; 
   bar: string;

    constructor(foo?: string, bar?: string) {
    this.foo = foo;
    this.bar = bar;
   }
}

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

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