Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

typechecking - 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?

Is this possible with TypeScript?

Note: TypeScript should also recognise that shape has a default constructor. In C# I would do something like this...

class ShapeMangler
{
    public void Mangle<T>() where T : new(), Shape
    {
        Shape shape = Activator.CreateInstance<T>();
        // mangle the shape
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...