1

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.

1
  • Use type: new() => T instead of type: typeof Base as buildObject parameter. Commented Sep 25, 2020 at 1:04

1 Answer 1

1

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);

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.