3

In TypeScript is there a way to extend a class with a generic type? Refer to my "hypothetical scenario" example where I want my class to have property called "breed" (or whatever):

interface dog {
  breed: string;
}

export class animal<T> extends T {
  legs: number;
}

export class main {
  private mydog: animal = new animal<dog>();

  constructor() {
    this.mydog.legs = 4;
    this.mydog.breed = "husky"; //<-- not conventionally possible, but basically want to acheive this
  }
}
John Weisz
  • 30,137
  • 13
  • 89
  • 132
MarzSocks
  • 4,229
  • 3
  • 22
  • 35

1 Answers1

0

You can't because classes are defined at compile time, and when the animal class is compiled T is not known.

You can however define a property of type T inside animal.

interface dog {

  breed: string;

}

export class animal < T > {
  actual: T;
  legs: number;
}

export class main {

  private mydog: animal < dog > = new animal < dog > ();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.actual.breed = "husky"; // this will fail because actual is undefined (you must set it too)
  }

}

I guess it depends on why you need the animal class to be generic, but you can also just have dog extend animal.

export class animal {
  legs: number;
}

class dog extends animal {
  breed: string;
}

export class main {

  private mydog: dog = new dog();

  constructor() {

    this.mydog.legs = 4;
    this.mydog.breed = "husky";
  }

}
toskv
  • 30,680
  • 7
  • 72
  • 74
  • Thanks for your response - sometimes in code - if you cant, you cant. – MarzSocks Mar 17 '16 at 09:07
  • @MarzSocks indeed, but if you can give us more information on why you'd need this setup maybe we can find a solution that better fits your needs. :) – toskv Mar 17 '16 at 11:38