简体   繁体   English

TypeScript类型检查类型而不是实例

[英]TypeScript type checking on type rather than instance

I want to be able to pass a type (rather than an instance of the type) as a parameter, but I want to enforce a rule where the type must extend a particular base type 我希望能够传递一个类型(而不是该类型的实例)作为参数,但是我想强制执行一个规则,其中该类型必须扩展特定的基本类型

Example

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.

Essentially I think I need to replace shape: Function with something...else? 从本质上讲,我认为我需要替换shape: Function用其他东西代替shape: Function

Is this possible with TypeScript? TypeScript可以实现吗?

Note: TypeScript should also recognise that shape has a default constructor. 注意:TypeScript还应该识别shape具有默认构造函数。 In C# I would do something like this... 在C#中,我会做这样的事情...

class ShapeMangler
{
    public void Mangle<T>() where T : new(), Shape
    {
        Shape shape = Activator.CreateInstance<T>();
        // mangle the shape
    }
}

There are two options: 有两种选择:

class ShapeMangler {
    public mangle<T extends typeof Shape>(shape: T): void {
        // mangle the shape
    }
}

Or 要么

class ShapeMangler {
    public mangle<T extends Shape>(shape: { new(): T }): void {
        // mangle the shape
    }
}

But both of these will be fine with the compiler: 但是这两种方法对于编译器都可以:

mangler.mangle(Circle);
mangler.mangle(NotAShape);

With the example you posted because your classes are empty, and an empty object matches every other object in structure. 在您发布的示例中,因为您的类为空,并且空对象与结构中的所有其他对象匹配。
If you add a property, for example: 如果添加属性,例如:

abstract class Shape {
    dummy: number;
}

Then: 然后:

mangler.mangle(NotAShape); // Error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM