0

Trying to extend a class with a static property, but I'm getting the following type error:

Property 'property' does not exist on type 'new (...args: any[]) => T'.(2339)

class A {
    static property = 'a'
}

class B extends A {}

function factory<T extends A>(type: new (...args: any[]) => T): T {
    if (type.property) { // error -> Property 'property' does not exist on type 'new (...args: any[]) => T'.(2339)
        console.log('heyyyyy')
    }

    return new type();
}

const b = factory(B);

console.log(B.property)

What must be done for this to work without the type error?

Thank you for your help.

2 Answers 2

2

To extend the answer by @mpstv (and avoid type cast)

type Constructor = new (...args: any) => any;

function factory<T extends typeof A & Constructor>(type: T): InstanceType<T> {
  if (type.property) {
    console.log('heyyyyy');
  }

  return new type();
}
Sign up to request clarification or add additional context in comments.

Comments

1

The answer to this question is here https://stackoverflow.com/a/49784147/14132148

Your factory will look like:

function factory<T extends typeof A>(type: T): InstanceType<T> {
  if (type.property) {
    console.log('heyyyyy');
  }

  return new type() as InstanceType<T>;
}

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.