Home > other >  How create a type for classes (not instances) extending a base class?
How create a type for classes (not instances) extending a base class?

Time:10-18

Please see question title and pseudo code of what I want below. How replace the any? Preferably not by making some huge manual union type.

    abstract class Letter {}
    
    class A extends Letter {}
    class B extends Letter {}
    class C extends Letter {}
    // potentially hundreds more "letters"

    type LetterClass = any
    
    const exampleUsage: LetterClass[] = [A, B, C]

attempting with typeof

type LetterClass = typeof Letter
const letters: LetterClass[] = [A, B, C]
const sample = letters[0]
new sample() // Cannot create an instance of an abstract class.

CodePudding user response:

You can use typeof keyword in typescript to create a type for your classes.

type LetterClass = typeof Letter;

CodePudding user response:

You can use a type like this: {new(): Letter}. Full example:

abstract class Letter {}
    
class A extends Letter {}
class B extends Letter {}
class C extends Letter {}
// potentially hundreds more "letters"

type LetterClass = {new(): Letter}

const letters: LetterClass[] = [A, B, C]
const sample = letters[0]
new sample()
  • Related