3

In TypeScript, is there a way for a class to refer to its constructor in a way that works when it is subclassed?

abstract class Base<T> {
  constructor(readonly value: T) {}

  abstract getName(): string;

  clone() {
    const Cls = this.constructor;
    return new Cls(this.value);
  }
}

In this snippet, Cls is given the type Function and so the compiler complains that: "Cannot use 'new' with an expression whose type lacks a call or construct signature."

1 Answer 1

5

Typescript does not use a strict type for the constructor (it just uses Function) and since this is not a constructor, it is not callable with new.

The simple solution is to use a type assertion:

abstract class Base<T> {
    constructor(readonly value: T) { }

    abstract getName(): string;

    clone() {
        // Using polymorphic this ensures the return type is correct in derived  types
        const Cls = this.constructor as new (value: T) => this;
        return new Cls(this.value);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.