Defining a subset of class as an interface

247 views Asked by At

I have a base generic class BaseModel and a set of subclasses which are the models to my solution. 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:

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. Is this possible in Typescript?


p.s. I am also considering the possibility of using the experimental decorators feature so the above Person model might look like:

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.

1

There are 1 answers

1
Niladri On

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();
    }

}