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

馋奶兔 提交于 2019-11-27 04:40:51

问题


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 extend that class and inherit the methods, will have their return types set to their respective this type. Like so:

class Model {
  save():this {    // return type: Model
    // save the current instance and return it
  }
}

class SomeModel extends Model {
  // inherits the save() method - return type: SomeModel
}

However, what I'm after is to have an inherited static method with a return type referencing the class itself. It's best described in code:

class Model {
  static getAll():Model[] {
    // return all recorded instances of Model as an array
  }

  save():this {
    // save the current instance and return it
  }
}

class SomeModel extends Model {
  // inherits the save() method - return type: SomeModel
  // also inherits getAll() - return type: Model (how can we make that SomeModel?)
}

Perhaps I'll have to think of a different way to implement this, since Polymorphic this in TypeScript 1.7 does not support static methods by design.

EDIT: I guess we'll see how this Github issue wraps up: https://github.com/Microsoft/TypeScript/issues/5863


回答1:


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

class BaseModel {

  static getAll<T>(this: { new(): T }): T[] {
    return [] // dummy impl
  }

  save(): this {
    return this  // dummy impl
  }
}

class SubModel extends BaseModel {
}

const sub = new SubModel()
const savedSub: SubModel = sub.save()
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




回答2:


What are you expecting this static method to return in the inherited subclass? Is it something like this:

class A {
    private static _instances = new Array<A>();
    static instances(): A[] { return A._instances; }
    constructor() { A._instances.push(this); }
}

class B extends A {

    static instances(): B[] { 
        return <B[]>(A.instances().filter(i => i instanceof B)); 
    }
    constructor() { super(); }; 
}

var a = new A();
var b = new B();

console.log(
     "A count: " + A.instances().length + 
    " B count: " + B.instances().length);

This will output "A count: 2 B count: 1". Or what are you expecting?



来源:https://stackoverflow.com/questions/34098023/typescript-self-referencing-return-type-for-static-methods-in-inheriting-classe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!