简体   繁体   English

将类的子集定义为接口

[英]Defining a subset of class as an interface

I have a base generic class BaseModel and a set of subclasses which are the models to my solution. 我有一个基本的通用类BaseModel和一组子类,它们是我的解决方案的模型。 What I'd LIKE TO DO is something like: 我想要做的是这样的:

export default class Person extends Model {
    public firstName: string;
    public lastName: string;
    public age: number;
    protected modelName: 'person';
}

And in the Model class let's say we have: Model类中,我们说:

export default abstract class Model {
    public lastUpdated: string;
    public createdAt: string;
    protected abstract modelName: string;
    // Public API
    public update(key, payload: any) { ... }
    public remove(key) { ... }
}

So what I'd like to be able to provide at design time is an interface which has all public properties but excludes the API functions. 因此,我希望能够在设计时提供一个具有所有公共属性但不包括API函数的接口。 Is this possible in Typescript? 在Typescript中可以吗?


ps I am also considering the possibility of using the experimental decorators feature so the above Person model might look like: ps我也在考虑使用实验装饰器功能的可能性,因此上述Person模型可能看起来像:

export default class Person extends Model {
    @property firstName: string;
    @property lastName: string;
    @property age: number;
    protected modelName: 'person';
}

Not sure if this provides any additional ways to achieve my goal as decorators in JS are uncharted territory for me. 由于JS中的装饰器对我来说是未知领域,因此不确定是否可以提供任何其他方式来实现我的目标。

Yes you can create an interface to put the public properties and then implement that interface in the derived class. 是的,您可以创建一个接口以放置公共属性,然后在派生类中实现该接口。 You can also inherit the base class in the same derived class. 您也可以在同一派生类中继承基类。

export interface IMyInterface {
    firstName: string;
    lastName: string;
    age: number;
    lastUpdated: string;
    createdAt: string;
}

export default abstract class Model {
    protected abstract modelName: string;
    // Public API
    public update(key:any, payload: any) { ... }
    public remove(key:any) { ... }
}



export default class Person extends Model implements IMyInterface {
    protected modelName:string = 'person';
    //implement other properties here
     constructor(){
      super();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM