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



我有一个通用方法

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

然后在实现中,假设我希望 T 的类型是命名空间 A 中的 B 类。

run <A.B> (options: A.B) : void 

错误是

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

."被读作","?我应该如何传递类型?

如果某个方法在基类中是泛型的,则不能只为派生类中的一个类型实现该方法。这将破坏 OOP 原则,因为您不能使用需要基类的派生类:

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 类型指定为泛型类型参数,不能在函数/方法声明中使用 type in 作为类型参数。这没有语法,因为它通常没有意义,如上所述。

一个不错的选择是将泛型类型参数移动到类中:

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

最新更新