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

Since it is Polymorphic in TypeScript 1.7, as I discovered here , we can define a method in a class with a return type this, and automatically, any classes that extend this class and inherit methods will have return types corresponding to their type this. For example:

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, I need to have an inherited method staticwith a return type that references the class itself. This is best described in the 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?)
}

I may have to think of another way to implement this, since Polymorphic thisin TypeScript 1.7 does not support design staticby design.

EDIT. , , Github : https://github.com/Microsoft/TypeScript/issues/5863 p >

+4
2

TypeScript 2.0+. { new(): T } this, , :

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

, getAll .

. https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics fooobar.com/questions/1618652/...

+8

, ? - :

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

"A count: 2 B count: 1". ?

0

Source: https://habr.com/ru/post/1618650/


All Articles