I'm trying to build an object factory in TypeScript where the objects generated must have a common base type, but I haven't figured out how to encode it properly.
Here's my current attempt which is incorrect because TypeScript says T is not guaranteed to be of type Base.
class Base {
constructor() {}
}
class User extends Base {
constructor() {
super()
}
}
class Post extends Base {
constructor() {
super()
}
}
function buildObject<T extends Base>(type: typeof Base): T {
return new type()
}
I thought I could just create a new type like type BaseInstance<T> = T extends Base to use here instead:
function buildObject<T>(type: typeof BaseInstance<T>): BaseInstance<T> {
return new type()
}
But this construct type BaseInstance<T> = T extends Base is invalid.
type: new() => Tinstead oftype: typeof BaseasbuildObjectparameter.