0

I am trying to create a function that takes a Class and returns function that can return the Class instance. However, it provides type information only for the base class and have an error when I try to create an instance in createFactory function. Playground

class BaseStore {
  public id = 1;
}

class OneStore extends BaseStore {
  public action() { }

  constructor(public a: string, public b: number) {
    super()
  }
}

function createFactory<T extends BaseStore, C extends new (...args: any) => T>(Create: C) {
  return (...args: ConstructorParameters<C>) => new Create(...args);
}

const oneFactory = createFactory(OneStore);
const one = oneFactory('s', 2);
one.id
one.action();

1 Answer 1

1

Typescript can't really resolve conditional types that still contain unresolved type parameters. You could write the types in a different way:

function createFactory<T extends BaseStore, P extends any[]>(Create: new (...args: P) => T) {
  return (...args: P) => new Create(...args);
}

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.