在打字稿中是否有“类”的类型? “任何”是否包括它?

在 Java 中,可以使用类型“ Class”给出一个 类转换为方法作为参数。我在类型脚本文档中没有发现任何类似的东西——是否有可能将类交给一个方法?如果是这样,那么“ any”类型是否包括这样的类类型?

背景: 我遇到了 Webstorm 的一个问题,它告诉我不能把角度2的课程交给 @ViewChild(...)。但是,类型脚本编译器不会抱怨。@ViewChild()的签名似乎是 "Type<any> | Function | string",所以我想知道是否包括类。

107911 次浏览

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

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

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);

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.

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);

Following worked for me:

type ClassRef = new (...args: any[]) => any;

my use case:

 interface InteractionType { [key: string]: ClassRef; }

Here's an example of a type that includes only classes:

declare type Class<T = any> = new (...args: any[]) => T;