是否可以像这样拥有带有默认值的可选构造函数参数
export class Test {
constructor(private foo?: string="foo", private bar?: string="bar") {}
}
这给了我以下错误:
参数不能有问号和初始化。
我想创建像
这样的实例x = new Test(); // x.foo === 'foo'
x = new Test('foo1'); // x.foo === 'foo1'
x = new Test('foo1', 'bar1');
实现此目标的正确 typescript 方法是什么?
最佳答案
根据定义,具有默认值的参数是可选的,如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
构造函数和其他函数一样,所以在你的情况下:
export class Test {
constructor(private foo: string = "foo", private bar: string = "bar") {}
}
关于javascript - 如何在 Typescript 中使用默认值定义可选的构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43326380/