打字稿类推断 [英] Typescript Class inference
问题描述
有谁知道如何在抽象泛型类中获取当前类?如何像CurrentClass"类型一样引用当前类而不仅仅是抽象类?
Does anyone know how to get the current class in an abstract-generic-class | how to reference the current class like a type "CurrentClass" and not just the abstract class?
原因:我正在编写一个小型库,它应该推断"当前类而不执行作为 CurrentClass"
reason: i'm writing a small library, that should "infer" the current class without doing "as CurrentClass"
abstract class Super {
public static create(args: keyof CurrentClass) {}
}
class CurrentClass extends Super {}
// to prevent
CurrentClass.create({} as CurrentClass);
我到处搜索,但找不到答案,所以在打字稿中甚至可能吗?
i searched everywhere, but couldnt find an answer to this, so is it even possible in typescript?
这个问题 会解决它,但不适用于静态函数
this question would solve it, but not for static functions
更新:似乎这个是我正在寻找的问题>
Update: it seems that this is the issue i was looking for
推荐答案
通常的解决方法是添加一个类型参数以从调用中推断目标:
The usual workaround is to add a type parameter to infer the target from the call:
abstract class Super {
s = ""
public static create<T>(this:new (...a: any[]) => T, args: keyof T) {}
}
class CurrentClass extends Super {
c = ""
}
// to prevent
CurrentClass.create("c"); // ok
CurrentClass.create("s"); // ok
这篇关于打字稿类推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!