【发布时间】:2020-02-11 16:00:07
【问题描述】:
在OOP中,除了在类实现的接口中声明的属性之外,还允许定义新的属性:
interface IIncapsuledData {
propertyA: number;
propertyB: string;
}
class TestClass implements IIncapsuledData {
public constructor(private incapsuledData: IIncapsuledData) { }
public get propertyA(): number { return this.incapsuledData.propertyA; }
public get propertyB(): string { return this.incapsuledData.propertyB }
// we can defined new getter without declaring new type alias or interface
public get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
我们可以对普通对象做同样的事情吗?
const objectWithoutClass: IIncapsuledData = {
propertyA: 2,
propertyB: 'b',
// Error! Object literal may only specify known properties.
get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
知道解决方案
声明新接口
interface IComputedData extends IIncapsuledData {
readonly newComputedProperty: string;
}
const objectWithoutClass: IComputedData = {
propertyA: 2,
propertyB: 'b',
get newComputedProperty(): string {
return `${this.propertyA}__${this.propertyB}`;
}
}
缺点:与class case不同,我需要声明新的接口。日常工作变得更多。一些优雅的解决方案,比如课堂案例?
【问题讨论】:
标签: typescript