TypeScript 类型检查类型而不是实例
TypeScript type checking on type rather than instance
我希望能够将类型(而不是类型的实例)作为参数传递,但我想强制执行类型必须扩展特定基类型的规则
例子
abstract class Shape {
}
class Circle extends Shape {
}
class Rectangle extends Shape {
}
class NotAShape {
}
class ShapeMangler {
public mangle(shape: Function): void {
var _shape = new shape();
// mangle the shape
}
}
var mangler = new ShapeMangler();
mangler.mangle(Circle); // should be allowed.
mangler.mangle(NotAShape); // should not be allowed.
基本上我想我需要用其他东西替换 shape: Function
?
TypeScript 可以做到这一点吗?
注意:TypeScript 还应识别 shape
具有默认构造函数。在 C# 中,我会做这样的事情...
class ShapeMangler
{
public void Mangle<T>() where T : new(), Shape
{
Shape shape = Activator.CreateInstance<T>();
// mangle the shape
}
}
有两种选择:
class ShapeMangler {
public mangle<T extends typeof Shape>(shape: T): void {
// mangle the shape
}
}
或
class ShapeMangler {
public mangle<T extends Shape>(shape: { new(): T }): void {
// mangle the shape
}
}
但是这两个都适用于编译器:
mangler.mangle(Circle);
mangler.mangle(NotAShape);
使用您发布的示例是因为您的 类 是空的,并且空对象与结构中的所有其他对象匹配。
如果加一个属性,例如:
abstract class Shape {
dummy: number;
}
然后:
mangler.mangle(NotAShape); // Error
我希望能够将类型(而不是类型的实例)作为参数传递,但我想强制执行类型必须扩展特定基类型的规则
例子
abstract class Shape {
}
class Circle extends Shape {
}
class Rectangle extends Shape {
}
class NotAShape {
}
class ShapeMangler {
public mangle(shape: Function): void {
var _shape = new shape();
// mangle the shape
}
}
var mangler = new ShapeMangler();
mangler.mangle(Circle); // should be allowed.
mangler.mangle(NotAShape); // should not be allowed.
基本上我想我需要用其他东西替换 shape: Function
?
TypeScript 可以做到这一点吗?
注意:TypeScript 还应识别 shape
具有默认构造函数。在 C# 中,我会做这样的事情...
class ShapeMangler
{
public void Mangle<T>() where T : new(), Shape
{
Shape shape = Activator.CreateInstance<T>();
// mangle the shape
}
}
有两种选择:
class ShapeMangler {
public mangle<T extends typeof Shape>(shape: T): void {
// mangle the shape
}
}
或
class ShapeMangler {
public mangle<T extends Shape>(shape: { new(): T }): void {
// mangle the shape
}
}
但是这两个都适用于编译器:
mangler.mangle(Circle);
mangler.mangle(NotAShape);
使用您发布的示例是因为您的 类 是空的,并且空对象与结构中的所有其他对象匹配。
如果加一个属性,例如:
abstract class Shape {
dummy: number;
}
然后:
mangler.mangle(NotAShape); // Error