Javascript 如何在 Typescript 中使用默认值定义可选的构造函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43326380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define optional constructor arguments with defaults in Typescript
提问by Jeanluca Scaljeri
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?
实现这一目标的正确打字稿方法是什么?
回答by Nitzan Tomer
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") {}
}

