Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

angular - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...