在TS中创建一组公共类属性

时间:2016-10-20 08:47:58

标签: typescript

我是打字稿的新手。

我有以下代码:

export interface MetaObject {
    public creationDate: string,
    public modificationDate: string
}

export class A implements MetaObject {
  constructor(
    public id:number,
    ) { }
}

export class B implements MetaObject {
  constructor(
    public id:number,
    ) { }
}

那么大的代码会触发这个错误:

TS2420 Class 'Booking' incorrectly implements interface 'MetaObject'.
  Property 'active' is missing in type 'Booking'.

我正在尝试使用MetaObject,其中某些属性我不想在我的构造函数中指定,但我希望在所有对象上存在。到目前为止,我已经创建了一个具有这些属性的接口,我的类正在实现它。这是正确的方法吗?这里的目的实际上不是要在类中添加任何其他东西,而是在界面中保留公共属性名称,类型......。

这是正确的方法吗?

1 个答案:

答案 0 :(得分:2)

不,这不是办法,一些事情:

(1)您在界面中放置的所有内容都是公开的,不需要指定属性是公共的,并且会导致错误。

(2)如果你实现了一个接口,你必须将这些属性添加到你的类中,否则编译器会抱怨:

  

类'A'错误地实现了接口'MetaObject'   “A”类型中缺少属性“creationDate”。

所以看起来应该是这样的:

interface MetaObject {
    creationDate: string;
    modificationDate: string;
}

class A implements MetaObject {
    constructor(
        public id: number,
        public creationDate: string,
        public modificationDate: string) { }
}

class B implements MetaObject {
    constructor(
        public id: number,
        public creationDate: string,
        public modificationDate: string) { }
}

code in playground

如果您不想重写实现,那么您需要一个基类:

abstract class MetaObject {
     constructor(
        protected creationDate: string,
        protected modificationDate: string) { }

     getCreationDate() {
         return this.creationDate;
     }

     getModificationDate() {
         return this.modificationDate;
    }
}

class A extends MetaObject {
    constructor(public id: number, creationDate: string, modificationDate: string) {
        super(creationDate, modificationDate);
    }
}

class B extends MetaObject {
    constructor(public id: number, creationDate: string, modificationDate: string) {
        super(creationDate, modificationDate);
    }
}

code in playground

另一种选择是use mixins,但我认为这对你的情况来说太过分了。

相关问题