首页 > 解决方案 > 当对象在 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}`;
    }
}

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

标签: typescript

解决方案


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

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

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

推荐阅读