【发布时间】:2019-10-23 18:18:13
【问题描述】:
考虑在模型-视图-控制器场景中用作数据模型的此类(我使用的是 TypeScript 3.5):
export class ViewSource {
private viewName : string;
private viewStruct : IViewStruct;
private rows : any[];
private rowIndex : number|null;
constructor(viewName : string) {
// Same as this.setViewName(viewName);
this.viewName = viewName;
this.viewStruct = api.meta.get_view_struct(viewName);
if (!this.viewStruct) {
throw new Error("Clould not load structure for view, name=" + (viewName));
}
this.rows = [];
this.rowIndex = null;
}
public setViewName = (viewName: string) => {
this.viewName = viewName;
this.viewStruct = api.meta.get_view_struct(viewName);
if (!this.viewStruct) {
throw new Error("Clould not load structure for view, name=" + (viewName));
}
this.rows = [];
this.rowIndex = null;
}
public getViewStruct = ():IViewStruct => { return this.viewStruct; }
public getCellValue = (rowIndex: number, columnName: string) : any => {
const row = this.rows[rowIndex] as any;
return row[columnName];
}
}
这不是一个完整的类,我只包含了几个方法来演示问题。 ViewSource 是一个可变对象。可以从应用程序的多个部分引用它。 (请注意,可变对象是事实。这个问题不是关于选择使用不可变对象的不同数据模型。)
每当我想更改ViewSource 对象的状态时,我都会调用它的setViewName 方法。它确实有效,但也非常笨拙。构造函数中的每一行代码都在setViewName 方法中重复。
当然不能使用这个构造函数:
constructor(viewName : string) {
this.setViewName(viewName);
}
因为这会导致 TS2564 错误:
Property 'viewStruct' has no initializer and is not definitely assigned in the constructor.ts(2564)
我一般不想忽略 TS2564 错误。但我也不想重复所有属性初始化。我还有一些其他类的属性更多(>10),相应的代码重复看起来很难看,而且容易出错。 (我可能忘记了有些东西必须通过两种方法进行修改......)
那么如何避免重复多行代码呢?
【问题讨论】:
标签: typescript3.0