查看我的代码:
interface IMyInterface{
a:string
b:string
c:number
//and more...
}
class MyClass extends IMyInterface{ //err 1
//the class has all fields from IMyInterface
constructor(opt:IMyInterface){
for(let key in opt){
this[key]=opt[key] //err2
}
}
myOtherMethods(){}
}
我希望一个类具有从接口(从HTTP请求返回)扩展的所有字段,并使用值自动构造它。上面的代码有2个错误:
类无法扩展接口,但是如果使用implements
,则需要再次编写该类中的所有字段和类型。
key
的类型是字符串,我无法在this
上访问它的字段。
答案 0 :(得分:0)
也许将IMyInterface
重写为类,然后扩展例如
class BaseClass {
public a: string = 'foo';
}
class MyClass extends BaseClass {
constructor() {
super();
console.log(this.a); // 'foo'
}
public someMethod() {
console.log(this.a); // 'foo'
}
}
接口仅是类型信息。它们没有任何语义含义(如默认值)
答案 1 :(得分:0)