[英]Typescript object initializer error for optional with default property declared in constructor shorthand
When declaring a constructor like this:像这样声明构造函数时:
export class Test {
constructor(
public name: string,
public value: number = -1) {
}
}
Keeping in mind that in the official TS documentation it is written:请记住,在官方 TS 文档中,它是这样写的:
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.
在所有必需参数被视为可选参数之后出现的默认初始化参数,就像可选参数一样,在调用它们各自的 function 时可以省略。
When trying this:尝试这个时:
let test: Test = {name: 'xxx'};
I get this error:我收到此错误:
TS2741: Property 'value' is missing in type '{ name: string;
TS2741:类型“{名称:字符串;”中缺少属性“值”; }' but required in type 'Test'.
}' 但在类型 'Test' 中是必需的。
And if I try to explicitly declare the parameter optional:如果我尝试显式声明可选参数:
public value?: number = -1
I get this one:我得到这个:
TS1015: Parameter cannot have question mark and initializer.
TS1015:参数不能有问号和初始值设定项。
There is a way to accomplish what you want.有一种方法可以完成你想要的。 You need to declare
value
as a public
property on your class and make it optional.您需要在 class 上将
value
声明为public
财产,并将其设为可选。 Then you can take in a parameter in your constructor called value
which will be local to that constructor function. Then in your constructor you can assign the value in the 'value' parameter to the 'value' property on your 'class' instance object.然后,您可以在构造函数中获取一个名为
value
的参数,该参数将是该构造函数 function 的本地参数。然后在您的构造函数中,您可以将“value”参数中的值分配给“class”实例 object 上的“value”属性。
class Test {
public value?: number;
constructor(
public name: string,
value: number = -1) {
this.value = value;
}
}
const a: Test = { name: '' };
const b= new Test('');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.