I'm currently grappling with developing an object factory in TypeScript that requires all generated objects to share a common base type. However, I'm encountering difficulty in properly defining this requirement.
Below is my current approach, which TypeScript identifies as incorrect because it cannot guarantee the type T 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 initially attempted to introduce a new type like
type BaseInstance<T> = T extends Base
for use in this context:
function buildObject<T>(type: typeof BaseInstance<T>): BaseInstance<T> {
return new type()
}
However, the syntax
type BaseInstance<T> = T extends Base
proved invalid.