打字稿:类类型的实例

时间:2020-05-05 21:31:01

标签: typescript

我的班级类型如A_Type

class A {
  constructor(public a: string) {}
}

type A_Type = {new (a: string): A}

并且我想获取A_Type构造函数实例的类型,以便我可以显式键入此函数

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)

我基本上是在打字稿中搜索typeof的反向操作。

3 个答案:

答案 0 :(得分:1)

function f<W extends { new(a: number): any }, R extends W extends { new(a: number): infer U } ? U : never>(e: W): R {
  return new e(2)
}

您需要使用泛型来提取返回类型。

但是,如果您一直期望A的实例,可以将其简化为

function f<W extends { new(a: number): A }>(e: W): A {
  return new e(2)
}

答案 1 :(得分:1)

我会遵循以下条件:

type Constructor<X> = {new (a: number): X}

function f<X>(e: Constructor<X>): X {
  return new e(2)
}

const w = f(A)

答案 2 :(得分:1)

您可以使用内置的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

Playground link