In Java, you can give a class to a method as a parameter using the type "Class". I didn't find anything similar in the typescript docs - is it possible to hand a class to a method? And if so, does the type "any" include such class-types?
Background: I'm having an issue with Webstorm, telling me that I cannot hand over a class to @ViewChild(...)
in Angular 2. However, the Typescript compiler does not complain. The signature of @ViewChild()
seems to be "Type<any> | Function | string"
, so I wonder if any includes Classes or not.
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 .
Summary. The TypeScript any type allows you to store a value of any type. It instructs the compiler to skip type checking. Use the any type to store a value that you don't actually know its type at the compile-time or when you migrate a JavaScript project over to a TypeScript project.
A TypeScript/JavaScript class is a function. A TypeScript type is just a definition that helps the TS compiler check the code. It is not translated to anything in the generated JS code.
The equivalent for what you're asking in typescript is the type { new(): Class }
, for example:
class A {} function create(ctor: { new(): A }): A { return new ctor(); } let a = create(A); // a is instanceof A
(code in playground)
The code above will allow only classes whose constructor has no argument. If you want any class, use new (...args: any[]) => Class
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