[英]Define new properties and methods for object when it implements some interface in TypeScript
[英]Typescript extend object that implements interface with dynamic properties
我有一个实现接口的 object:
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 '.
如何使用 object 文字在接口上进行扩展
@Tomas Katz,您错误地实现了一个接口,您在SomeClass
类型的ILoadedComponent
组件中创建了属性。
如果你想实现一个接口并添加新属性,你必须使用它,如下所示
class SomeClass implements ILoadedComponent{
property1: 'x',
property2: 10,
property3: 'y',
property4: 60
}
如果你想在SomeClass
中使用loadedComponent
属性,那么你必须创建一个单独的 class 来实现接口,或者你必须在另一个接口中extend
ILoadedComponent
接口并在SomeClass
中使用该接口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.