TypeScript:在泛型中使用命名空间类型参数

TypeScript: Use namespaced type argument in generic

我有一个通用方法

abstract run<T> (options: T): void;

然后在实现中,假设我希望 T 的类型为命名空间 A 中的 class B。如果我使用

,TSLint 会抱怨
run <A.B> (options: A.B) : void 

错误是

Type '<A, B>(options: B) => void' is not assignable to type '<T>(options: T) => void'

好像是点'.'被读作 ',' 吗?我应该如何传递类型?

如果一个方法在基 class 中是通用的,则它不能在派生 class 中只为一种类型实现。这会破坏 OOP 原则,因为您不能在预期基础 class 的地方使用派生的 class:

namespace A {
    export class B { private x!: string}
}
abstract class Abs {
    abstract run<T>(p: T): void;
}
class Impl extends Abs{
    run(p: A.B) { } // We get an error here as we should but if this were allowed we would get the error below
}

let a: Abs = new Impl();
a.run(""); // Impl expects A.B, but Abs will let us pass in any T not ok

注意你使用的语法也是错误的,你只能在调用中指定concerte类型作为泛型类型参数,你不能使用一个类型作为in中的类型参数function/method 声明。没有语法,因为它通常没有意义,如上所述。

一个不错的选择是将泛型类型参数移至 class:

namespace A {
    export class B { private x!: string}
}
abstract class Abs<T> {
    abstract run(p: T): void;
}
class Impl extends Abs<A.B>{
    run(p: A.B) { } // ok now
}

let a: Abs<A.B> = new Impl();
a.run(new A.B()); // type safe