I would like to pass type information for class, with hinting the compiler that the given parameter is not an instance of a class but the class definition. How can I do that?
import * as Routes from '../routes';
import * as Entities from '../entities';
export class RouteManager {
public router = Router();
private connection = getConnectionManager().get();
constructor() {
this.addRoute(Routes.VideoRoute, Entities.Video);
}
addRoute(routeClass: AbstractRoute<AbstractEntity>, entity: AbstractEntity): void {
const instance = new routeClass(entity, this.connection.getRepository(entity))
this.router.get(instance.route, instance.find);
}
}
Here the compiler complains about the new routeClass(entity, this.connection.getRepository(entity))
line because it thinks routeClass
is an instance of AbstractRoute<AbstractEntity>
and not the exported class definition for it.
I have tried usingAbstractRoute<AbstractEntity>.constructor
but Typescript doesn't seem to know this structure.
TypeScript treats a class as both value and type. This implicit type declared by TypeScript describes the shape of the instance a class produces. Therefore when a class is used as a type, such as using let value :Class annotation, TypeScript checks if the value has all the public properties of the Class .
To define user-specific information about a class definition. A class parameter is simply an arbitrary name-value pair; you can use it to store any information you like about a class. To define a class-specific constant value. To provide parameterized values for method generator methods to use.
Defining Classes. To declare a class, we use the class keyword. For example, to declare a simple class, we can write: Class declarations aren't hoisted so they can't be used before they're defined in the code — the TypeScript compiler will not automatically pull them up to the top.
TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class's field are the same.
The syntax for this looks a little bit weird. Basically you define a signature that uses something like new(...args: any[]) => T
. You of course can be more strict by replacing T
with your class and the args
with the constructor
signature.
I would recommend something like this:
class Foo {}
type Constructor<T> = new(...args: any[]) => T;
function createFoo(thing: Constructor<Foo>) { return new thing(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With