Typescript类的静态推断

问题描述 投票:0回答:1
import { FilterQuery } from "mongodb";

abstract class Base<T extends Base<any>> {
    public static async findOne<T extends Base<any>>(
        this: new (...a: any[]) => T,
        query: FilterQuery<T>
    ): Promise<T> {
        console.log(this.getSomeString()); // currently: "getSomeString" dosnt exists on type "new (...a: any[]) => T"
        // already tried "typeof T" - because "typeof" is not allowed on generics
        // already tried https://stackoverflow.com/a/52358194/8944059 's static solution
        // already tried "T" - which makes "this: any"
        // and i tried various other things, which resulted in "await SomeExtendingClass" cannot be assigned to "this"

        return undefined;
    }

    public static getSomeString(): string {
        return "Hello";
    }
}

class SomeExtendingClass extends Base<SomeExtendingClass> {
    public someValue: string;
}

(async () => {
    await SomeExtendingClass.findOne({ someValue: "hi" });
})();

目标将在this中具有所有静态变量,同时能够用new this(...args)对其进行调用,并且(父类的)所有键都可插入query中,而不必删除abstract

已经尝试过:-https://stackoverflow.com/a/58037767/8944059-https://stackoverflow.com/a/52358194/8944059的静态解决方案

PS:我不了解打字稿类型的大部分魔力,这就是为什么我要问...

PPS:here is the project i would need it

typescript inheritance type-inference
1个回答
0
投票

感谢@jcalz

© www.soinside.com 2019 - 2024. All rights reserved.