nickf
nickf

Reputation: 545985

Writing a generic clone method in TypeScript

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."

Upvotes: 3

Views: 654

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

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

Upvotes: 5

Related Questions