Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a type for "Class" in Typescript? And does "any" include it?

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.

like image 761
Florian Gössele Avatar asked Sep 08 '16 13:09

Florian Gössele


People also ask

Can a class be a type in TypeScript?

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 .

Is any a type in TypeScript?

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.

What is the difference between type and class in TypeScript?

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.


1 Answers

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

like image 135
Nitzan Tomer Avatar answered Sep 18 '22 18:09

Nitzan Tomer