TypeScript:将类型转换回实例



我有创建给定类实例的函数,我不知道如何告诉TypeScript:
函数生成器返回在第一个参数中传递的类的实例

class A extends HTMLElement {
  color: 'white'
}
function builder<T extends typeof HTMLElement>(classParam: T) {
  let instance = new classParam()
  return instance
}
let instance = builder(A)
instance.color = 'black'
// Property 'color' does not exist on type 'HTMLElement'

是否可以不使用类型断言?

我已经修复并解释了这些问题:

class A extends HTMLElement {
  color: string = 'white' // you gave it the type "white", 
                          // but I assume you need the value "white" (and type `string`)
}

function builder<T extends HTMLElement>(classParam: { new(): T }) : T { 
  // previous line:
  // - `typeof` in the generic constraint is not valid
  // - the parameter could not be of type `T`, because you would not be 
  //   able to use `new`. It's now a parameter which has a constructor
  //    which creates a `T`
  // - we are now returning `T`, instead of (implicit) `any`
  let instance = new classParam()
  return instance
}
let instance = builder(A)
instance.color = 'black'

链接到游乐场

最新更新