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

后端 未结 3 549
野的像风
野的像风 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:27

    Based on the simplest answer to the GitHub issue, you can use InstanceType<> like this:

    class Foo {
        static create(this: T): InstanceType {
            return new this() as InstanceType
        }
    
        static getAll(this: T): Array> {
            return []
        }
    }
    
    class Bar extends Foo { }
    
    const a = Bar.getAll() // typeof a is Bar[]
    const b = Bar.create() // typeof b is Bar.
    

    Where I threw in the create function just for illustration, from the linked GitHub example.

提交回复
热议问题