Instantiating child class from a static method in base class, using TypeScript

前端 未结 2 1555
情歌与酒
情歌与酒 2020-12-31 08:51

Being new to TypeScript, what is the best method to implement a static factory in a base class that instantiates the child class type. For instance, consider a findAl

2条回答
  •  感情败类
    2020-12-31 09:51

    You will need to pass the subtype constructor to the static function on the base type.

    This is because the base class doesn't (and shouldn't) know anything about the subtypes to know which child constructor to use.

    This is an example of how it might look - each subtype defines its own static findAll() method that calls the standard behaviour on the parent class, passing the data and constructor along for the parent to use:

    class BaseModel {
        static data: {}[];
    
        static _findAll(data: any[], Type): T[] {
            return data.map((x) => new Type(x));
        }
    
        constructor(readonly attributes) {
        }
    }
    
    class Model extends BaseModel {
        static data = [{ id: 1 }, { id: 2 }];
    
        constructor(attributes) {
            super(attributes);
        }
    
        static findAll() {
            return BaseModel._findAll(this.data, this);
        }
    }
    
    const a = Model.findAll();
    

提交回复
热议问题