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
Type<T>
from @angular/core
is a proper interface for Class.
export interface Type<T> extends Function {
new (...args: any[]): T;
}
You can use it to keep reference to class, instead of instance of this class:
private classRef: Type<MyCustomClass>;
or
private classRef: Type<any>;
According to background of your question with @ViewChild
:
@ViewChild allows to inject "string selector"
/ Component
/ Directive
Signature of Type<any> | Function | string
is an abstract signature that allows us to inject all of above.
Following worked for me:
type ClassRef = new (...args: any[]) => any;
my use case:
interface InteractionType { [key: string]: ClassRef; }
The simplest solution would be let variable: typeof Class
.
Here an example:
class A {
public static attribute = "ABC";
}
function f(Param: typeof A) {
Param.attribute;
new Param();
}
f(A);
Angular internally declare Type
as:
export interface Type<T> extends Function { new (...args: any[]): T; }
With TypeScript3 it should be possible to add types for arguments without function overloading:
export interface TypeWithArgs<T, A extends any[]> extends Function { new(...args: A): T; }
Example:
class A {}
function create(ctor: Type<A>): A {
return new ctor();
}
let a = create(A);
is it possible to hand a class to a method? And if so, does the type "any" include such class-types?
Yes and yes. any
includes every type.
Here's an example of a type that includes only classes:
type Class = { new(...args: any[]): any; };
Then using it:
function myFunction(myClassParam: Class) {
}
class MyClass {}
myFunction(MyClass); // ok
myFunction({}); // error
You shouldn't have an error passing in a class for Function
though because that should work fine:
var func: Function = MyClass; // ok
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