[英]Generic constructor reference and static method in TypeScript
Please, consider the following code:请考虑以下代码:
class Wrapper<T> {
public static forConstructor<S extends Object>(construc: { new (...args: any[]): S }): Wrapper<S> {
return new Wrapper<S>();
}
}
class A {
private aaa: string = null;
}
class B {
private bbb: string = null;
}
const wrapper: Wrapper<A> = Wrapper.forConstructor(B);// LINE X
At LINE X Wrapper<A> = Wrapper<B>
that is an wrong, however, TypeScript doesn't show error at this line.在 LINE X
Wrapper<A> = Wrapper<B>
这是错误的,但是,TypeScript 不会在此行显示错误。 What is my mistake?我的错误是什么?
Currently Wrapper<A>
and Wrapper<B>
are structurally compatible.目前
Wrapper<A>
和Wrapper<B>
在结构上是兼容的。 If you'll store the passed constructor as a field (for example) you'll get an error:如果您将传递的构造函数存储为一个字段(例如),您将收到一个错误:
type Constructor<T> = new (...args: any[]) => T;
class Wrapper<T> {
constructor(private c: Constructor<T>){}
public static forConstructor<T>(construc: Constructor<T>): Wrapper<T> {
return new Wrapper<T>(construc);
}
}
class A {
private aaa: string = null;
}
class B {
private bbb: string = null;
}
const wrapper: Wrapper<A> = Wrapper.forConstructor(B); // error
A static method can not use the instance type argument Wrapper<T>
since static is not instance bounded.静态方法不能使用实例类型参数
Wrapper<T>
因为静态方法不受实例限制。 Your method signature <S extends Object
essentially means any
Object.您的方法签名
<S extends Object
本质上意味着any
Object。 So there is no type safety at all.所以根本就没有类型安全。 That's why the tscompiler does not complain at
这就是为什么 tscompiler 不会抱怨
const wrapper: Wrapper<A> = Wrapper.forConstructor(B);// LINE X
However if you actually use the instance type argument and make it non-static then it will complain eg但是,如果您实际使用实例类型参数并将其设为非静态,那么它会抱怨,例如
class Wrapper<S> {
public forConstructor(construc: { new (...args: any[]): S }): Wrapper<S> {
return new Wrapper<S>();
}
}
const wrapper: Wrapper<A> = new Wrapper();
wrapper.forConstructor(B); // will not work
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.