Reputation: 33537
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.
Upvotes: 1
Views: 390
Reputation: 42188
Try defining a type BaseConstructor which can be called via the new
keyword and return an instance of Base. Your classes Base, User, and Post all fulfill this type definition.
type BaseConstructor<T extends Base> = new() => T;
function buildObject<T extends Base>(type: BaseConstructor<T>): T {
return new type();
}
const myObj: Post = buildObject(Post);
Upvotes: 1