typescript扩展基类对象属性
问题描述:
首先,我很抱歉,我完全不熟悉面向对象编程,并且我确信有更好的方法来说出这个问题(可能会产生搜索结果或10) 。typescript扩展基类对象属性
因此,为了使我的生活轻松,并解释我想在这里做的代码
class A {
propertyA = {
itemA: "a",
itemB: "b".
itemC: "c"
}
propertyB = {
itemA: "A"
}
}
class B extends A {
propertyA.itemD = "d";
propertyB.itemB = "B";
}
我得到一个错误,当我尝试这样做。我基本上需要基类作为模板,并在扩展类中扩展一些东西。否则,只需要所有其他属性(我只是不想重新输入他们每类)
答
这是你如何做到这一点的打字稿
class A {
propertyA = {
itemA: "a",
itemB: "b".
itemC: "c"
}
propertyB = {
itemA: "A"
}
}
class B extends A {
constructor(){
super();
this.propertyA.itemD = "d";
this.propertyB.itemB = "B";
}
}
var x = new B();
console.log(x.propertyA.itemD);
答
接受的答案还是给了我打字稿警告,当输入我的对象属性。您可以抑制property does not exist on type
警告,如果你必须完全重新申报父对象的属性选项,如下所示:
class A {
propertyA: {
itemA: string
} = {
itemA: '123'
};
}
class B extends A {
propertyA: {
itemA?: string, // Need to re-declare this
itemB?: string
} = {
itemA: '123', // Need to re-initialise this
itemB: '456'
};
}
这个工作最好的,如果你的时候都宣称不初始化属性,而是在构造函数或其他方法如果可能。这就意味着,你不需要知道什么A级初始化的属性,除非你专门重写它:
class A {
propertyA: {
itemA?: string
} = {};
constructor() {
this.propertyA.itemA = '123'; // Now we don't need to do this in derived classes
}
}
class B extends A {
propertyA: {
itemA?: string, // Need to re-declare this
itemB?: string
} = {};
constructor() {
super();
this.propertyA.itemB = '456';
}
}
答
不知道这是否是解决它的正确的方法,但是这是我结束了:
class A {
propertyA: any = {
itemA: 'a',
itemB: 'b',
itemC: 'c'
}
propertyB: any = {
itemA: 'A'
}
}
class B extends A {
propertyA: any = {
...this.propertyA,
...{
itemD: 'd'
}
};
propertyB: any = {
...this.propertyB,
...{
itemB: 'B'
}
}
}
B类的一个新实例将有{ itemA: 'a', itemB: 'b', itemC: 'c', itemD: 'd' }
为propertyA
和{ itemA: 'A', itemB: 'B' }
作为propertyB
*叹*我知道这将是可笑的东西容易。很容易回答。标记和upvoted。 – Akidi
这是我想念普通ol'javaScript的东西。动态扩展对象的能力 –