【问题标题】:Define new properties and methods for object when it implements some interface in TypeScript当对象在 TypeScript 中实现某些接口时,为对象定义新的属性和方法
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答!所以,TypeScript 允许的内容是最简洁的......
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 2017-08-08
    • 2018-07-13
    • 1970-01-01
    • 2020-09-19
    • 2022-12-04
    • 2018-06-02
    • 2021-07-21
    相关资源
    最近更新 更多