我有创建给定类实例的函数,我不知道如何告诉TypeScript:
function builder返回在第一个参数
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'
是否可以不使用类型断言?
答案 0 :(得分:2)
我已修复并解释了问题:
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'
链接到playground