Hinting abstract classes in TypeScript

Viewed 163

I have an array of classes, all of which extend from a base abstract class. If you'll forgive the terrible and overused OO abstractions:

abstract class Animal {
  abstract speak(): string;
}

class Dog extends Animal {
  speak(): string {
    return "woof... sigh"
  }
}

class Cat...

I have an array which encapsulates all of these implementations:

const all = [Cat, Dog];

I want to tell TypeScript that everything in this array will, on construction, return a class that is an instance of Animal.

It's important to note that this is passing around the class, not the object, so this would be invalid as the classes themselves don't inherit from the abstract.

const all : Array<Animal> = [Cat, Dog]

I unfortunately can't seem to find anything in the docs about typehinting through the new keyword.

2 Answers

We want to declare a value which, when called with new, returns an Animal. This is written as:

new() => Animal

Note the similarity to function types (() => Animal).

The full code is then:

const all: Array<new() => Animal> = [Cat, Dog];

Or, using an interface for clarity:

interface AnimalConstructor {
    new(): Animal;
}

const all: AnimalConstructor[] = [Cat, Dog];

You should be able to do this:

const all: (typeof Animal)[] = [Cat, Dog]
Related