Naz*_*ain 6 javascript typescript
我有一个场景,我需要在构造函数之外初始化类属性。考虑以下示例。
\n\nclass A {\n public prop: MyPropType;\n public id: string;\n\n public constructor(id: string) {\n this.id = id;\n }\n\n public init(value: string): void {\n this.prop = new MyPropType(value);\n }\n\n public toString(): string {\n return `${this.id} - ${this.prop.toString()}`;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n在上面的场景中我得到了错误:
\n\nTS2564: Property \xe2\x80\x98 prop\xe2\x80\x99 has no initializer and is not definitely assigned in the constructor.\nRun Code Online (Sandbox Code Playgroud)\n\n如果我将该属性设置为可选,prop?: MyPropType那么它就会开始抱怨其使用情况。
TS2532: Object is possibly \'undefined\'.\nRun Code Online (Sandbox Code Playgroud)\n\n这两个错误都是可以理解的。我正在 Typescript 中寻找正确的方式和方法来解决这种情况。
\n\n我们应该as在每次使用时都使用例如(this.prop as MyPropType).toString(),还是有其他 Typescript 方式?
如果我们对函数的使用做出断言,为什么 Typescript 无法识别它?
\n\nTS2564: Property \xe2\x80\x98 prop\xe2\x80\x99 has no initializer and is not definitely assigned in the constructor.\nRun Code Online (Sandbox Code Playgroud)\n\nTypescript 有什么办法可以识别上述场景并感觉良好吗?
\n我最终使用以下模式解决了上述问题,而无需更改与 typescript 或 tslint 相关的任何配置。
class A {
private _prop?: MyPropType;
public id: string;
public constructor(id: string) {
this.id = id;
}
public init(value: string): void {
this._prop = new MyPropType(value);
}
public get prop() : MyPropType {
return this._prop as MyPropType;
}
public toString(): string {
return `${this.id} - ${this.prop.toString()}`;
}
}
Run Code Online (Sandbox Code Playgroud)
使用这种方法,值prop在构造函数外部初始化,并且仍然可以访问代码中的 prop,而不会出现任何警告或 linting 错误。
| 归档时间: |
|
| 查看次数: |
3129 次 |
| 最近记录: |