Here's a valid typescript snippet:
class A{
}
// what is the type of x ? i.e. f( x: <TYPE HERE>)...
function f(x) {
return new x();
}
const t = f(A);
It is obvious that the type of x is the type of the constructor function but it is not clear to me how one would specify it in Typescript.
Is it possible to type the parameter x ?
If yes, what is the type?
You can use:
interface Newable<T> {
new (): T;
}
As follows:
class A {}
interface Newable<T> {
new (): T;
}
function f(x: Newable<A>) {
return new x();
}
const t = f(A);
If you want to allow constructor arguments you will need to type them:
class A {
constructor(someArg1: string, someArg2: number) {
// ...
}
}
interface Newable<T> {
new (someArg1: string, someArg2: number): T;
}
function f(x: Newable<A>) {
return new x("someVal", 5);
}
const t = f(A);
And you could also do something more generic if needed:
interface Newable<T> {
new (...args: any[]): T;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.