I have the type of a class like here as A_Type?
class A {
constructor(public a: string) {}
}
type A_Type = {new (a: string): A}
Run Code Online (Sandbox Code Playgroud)
And Id like to get the type of the instance of the A_Type constructor, so that I could type this function explicitly
class A {
constructor(public a: number) {}
}
// ** not working **
function f<W extends { new(a: number): A }>(e: W): instanceof W {
return new e(2)
}
let w = f(A)
Run Code Online (Sandbox Code Playgroud)
I am basically searching for the reverse operation of typeof in typescript.
您可以使用内置实用InstanceType<T>程序来执行此操作
class A {
constructor(public a: number) { }
}
// declare that the return value of the class constructor returns an instance of that class
function f<W extends { new(a: number): InstanceType<W> }>(e: W) {
return new e(2) // return type is automatically inferred to be InstanceType<W>
}
let w = f(A) // w: A
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10585 次 |
| 最近记录: |