在TypeScript中实现某些接口时,为对象定义新的属性和方法

时间:2019-10-15 03:17:43

标签: typescript

在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}`;
    }
}

缺点:与类情况不同,我需要声明新接口。日常工作变得更多。一些优雅的解决方案,例如在课堂案例中?

1 个答案:

答案 0 :(得分:1)

您可以使用相交类型,并与索引器相交:

interface IEncapsuledData {
    propertyA: number;
    propertyB: string;
}

const objectWithoutClass: IEncapsuledData & { [key: string]: any } = {
  propertyA: 1,
  propertyB: '2',
  propertyC: 3
};