定义类的一个子集作为接口

定义类的一个子集作为接口

问题描述:

我有一个基本泛型类BaseModel和一组子类,它们是我的解决方案的模型。我想要做的是一样的东西:定义类的一个子集作为接口

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

而在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) { ... } 
} 

那么想我能够在设计时是提供一个具有所有公共属性但不包含API函数的接口。在打字稿中这可能吗?


p.s.我也在考虑使用实验装饰功能的可能性,因此,上述人模式可能类似于:

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

不知道这是否提供任何附加的方式来实现我的目标是在JS装饰是一个未知的领域我。

是的,您可以创建一个接口来放置公共属性,然后在派生类中实现该接口。您也可以继承相同派生类中的基类。

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

} 
+0

是的,这是真的,但我希望是没有必要定义接口_and_然后将公共属性添加到类。似乎像TS拔/挑/或映射键可能能够实现这一点?也很可能为API定义一个接口,然后我可以从公共接口中排除API吗? – ken