Typescript: how to return subclass type from inherited static property?

前端 未结 1 2062
耶瑟儿~
耶瑟儿~ 2020-12-19 09:02
class BaseDoc {
    static Collection;  
    static find(){
        // which is expected to return an instance of SubDoc when run SubDoc.find()
        return this.C         


        
1条回答
  •  借酒劲吻你
    2020-12-19 09:48

    You can create a generic version of find that will have the this parameter inferred to the type of the class it's being called on, and use InstanceType to extract the actual instance type from the class type:

    class BaseDoc {
        static Collection: any;
        static find(this: T): InstanceType {
            // which is expected to return an instance of SubDoc when run SubDoc.find()
            return this.Collection.find();
        }
    }
    
    class SubDoc extends BaseDoc {
    
    }
    
    SubDoc.find() // return SubDoc
    

    Or you can mandate that the derived class defines a generic Collection member of the appropriate type:

    class Collection {
        find(): T {
            return null as any // dummy imeplmentation
        }
    }
    type GetCollectionItem> = T extends Collection ? U: never;
    
    class BaseDoc {
        static Collection: Collection;
        static find }>(this: T):  GetCollectionItem {
            // which is expected to return an instance of SubDoc when run SubDoc.find()
            return this.Collection.find();
        }
    }
    
    class SubDoc extends BaseDoc {
        static Collection: Collection;
    }
    
    SubDoc.find() // return SubDoc
    

    0 讨论(0)
提交回复
热议问题