Dan*_*ruz 8 generics typescript
我对 Typescript 和泛型相当陌生;我一定错过了一些希望微不足道的东西。
我试图传递一个(通用)类作为函数的参数,但该类从另一个特定类扩展
一个过于简单的例子如下:假设我有
class A {
static generate3() { return [new A(),new A(),new A()]; }
}
class B extends A {}
class C extends A {}
Run Code Online (Sandbox Code Playgroud)
我想要一个方法,可以使用从 A 继承的任何类作为参数来调用该方法,并返回该静态方法的结果。就像是
f(B) // returns type B[]
Run Code Online (Sandbox Code Playgroud)
我想我能做到
function f(type: typeof B){
return type.generate3();
}
Run Code Online (Sandbox Code Playgroud)
但这需要我提前定义好类。我也不能使用 typeof B|typeof C 因为在现实生活中有太多的类,这不实用我尝试过
function f2<T>(type: typeof T extends A){
return type.hello();
}
Run Code Online (Sandbox Code Playgroud)
whereT应该是类,但它会抛出以下错误:'T' only refers to a type, but is being used as a value here.
我认为这有效
function f3(type: typeof A){
return type.generate3();
}
Run Code Online (Sandbox Code Playgroud)
但 f3(B) 的返回类型仍然是 A[] 而不是所需的 B[] 我尝试将两者混合,如下所示:
function f4<T extends A>(type: typeof A) : T[]{
return type.generate3() as T[]; // cast it
}
Run Code Online (Sandbox Code Playgroud)
但是返回类型f4(B)还是A[]
不太明白。谁能弄清楚我做错了什么吗?
| 归档时间: |
|
| 查看次数: |
937 次 |
| 最近记录: |