问题:我想通过向其中定义的对象添加其他属性来扩展类。这是场景:
我定义了以下类:
export class SiteProperties {
properties : {
name: string;
}
}
我将此类用作以下类的构建块
export class Site extends SiteProperties {
parent : SiteProperties[];
online: number;
issues: number;
}
问题是我想扩展SiteProperties以在'属性中包含其他字段。对象,使它成为:
export class SitePropertiesDetails {
properties : {
name: string,
description: string // I basically want to add this field by extending the first SiteProperties class I created
}
}
有关如何通过某种方式扩展原始name
类来避免重复上一个SitePropertiesDetails
类内的SiteProperties
属性的任何想法?
答案 0 :(得分:1)
正如James Monger指出的那样,也许这不是一条路?
如果它是您想要的,那么您可以使用带有可选参数的接口来定义properties
对象:
interface ISiteProperties {
parent?: SiteProperties[];
online?: number;
issues?: number;
name?: string;
description?: string;
}
class SiteProperties {
public properties: ISiteProperties = {};
constructor() {
this.properties.name = "Test name";
}
}
class Site extends SiteProperties {
constructor() {
super();
this.properties.online = 123;
this.properties.issues = 321;
}
}
var obj1 = new SiteProperties(), obj2 = new Site();
console.log(obj1);
console.log(obj2);

和javascript版本:
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var SiteProperties = (function () {
function SiteProperties() {
this.properties = {};
this.properties.name = "Test name";
}
return SiteProperties;
}());
var Site = (function (_super) {
__extends(Site, _super);
function Site() {
_super.call(this);
this.properties.online = 123;
this.properties.issues = 321;
}
return Site;
}(SiteProperties));
var obj1 = new SiteProperties(), obj2 = new Site();
console.log(obj1);
console.log(obj2);

答案 1 :(得分:0)
我要说最好的OOP方法是在类本身上拥有属性,而不是在匿名对象中。
export class SiteProperties {
name: string;
}
export class Site extends SiteProperties {
parent: SiteProperties[];
online: number;
issues: number;
}
export class SitePropertiesDetails extends SiteProperties {
description: string;
}
let x = new SitePropertiesDetails();
x.name = "Site Number One";
x.description = "The best site there is!";
如您所见,SitePropertiesDetails
同时包含name
和description
。这符合您的需求吗?