Typescript扩展对象,实现具有动态属性的接口

时间:2020-05-14 13:24:41

标签: typescript

我有一个实现接口的对象:

interface ILoadedComponent {
    property1:string;
    property2: numberl;
}
class SomeClass {
    loadedComponent:ILoadedComponent = {
        property1:'x',
        property2: 10
    }
}

但是我想在实现的接口上增加其他属性:

class SomeClass {
        loadedComponent:ILoadedComponent = {
        property1: 'x',
        property2: 10,
        property3: 'y',
        property4: 60
    }
}

为了扩展已实现的接口,我会遇到编译器错误:

 ... is not assignable to type SomeClass ...
Object literal may only specify known properties, and 'property3' does not exist in type 'SomeClass '.

如何在带有对象常量的接口上花费

1 个答案:

答案 0 :(得分:0)

@Tomas Katz,您错误地实现了一个接口,您在SomeClass类型的ILoadedComponent中创建了该属性。

如果要实现接口并添加新属性,则必须按如下所示使用它

class SomeClass implements ILoadedComponent{
        property1: 'x',
        property2: 10,
        property3: 'y',
        property4: 60
}

如果要在loadedComponent中使用SomeClass属性,则必须创建一个单独的类来实现该接口,否则必须在另一个extend ILoadedComponent接口中使用界面并在SomeClass

中使用该界面