我有以下构造函数:
constructor(@Optional() private config?: DefaultConfig) {
this.config = config || new DefaultConfig();
}
有什么方法可以避免使用this.config = config || new DefaultConfig();
吗?我想要的是在构造函数的参数中添加默认值?如下所示:
constructor(@Optional() private config?=new DefaultConfig(): DefaultConfig) {}
谢谢!
发布于 2016-10-20 22:50:47
所以我对Angular2并不熟悉,但是在纯TypeScript中,下面的内容可以达到你的目的:
constructor(private config = new DefaultConfig()) {}
也就是说,如果没有传递配置,this.config
将是一个新的DefaultConfig
。它还确保构造函数参数必须是DefaultConfig
类型。
发布于 2017-03-17 05:33:43
你有没有尝试过下面的方法?
constructor(@Optional() private config: DefaultConfig=new DefaultConfig()) {
..
}
注意:在之前不再使用?
https://stackoverflow.com/questions/40165076
复制相似问题