TypeScript: self-referencing return type for static methods in inheriting classes

后端 未结 3 554
野的像风
野的像风 2020-12-03 07:12

With Polymorphic this in TypeScript 1.7, as I discovered here, we can define a method in a class with a return type of this, and automatically, any classes that

3条回答
  •  时光说笑
    2020-12-03 07:34

    This is doable in TypeScript 2.0+. By using an inline { new(): T } type to capture this, you'll get what you wanted:

    type Constructor = { new (): T }
    
    class BaseModel {
      static getAll(this: Constructor): T[] {
        return [] // dummy impl
      }
    
      /**
       * Example of static method with an argument:
       */
      static getById(this: Constructor, id: number): T | undefined {
        return // dummy impl
      }
    
      save(): this {
        return this // dummy impl
      }
    }
    
    class SubModel extends BaseModel {}
    
    const sub = new SubModel()
    const savedSub: SubModel = sub.save()
    
    // Behold: SubModel.getAll() returns SubModels, not BaseModel
    const savedSubs: SubModel[] = SubModel.getAll()
    

    Note that getAll still expects no arguments with this typing.

    For more information, see https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics and https://stackoverflow.com/a/45262288/1268016

提交回复
热议问题