![]() |
VOOZH | about |
TypeScript Using class types in generics allows you to create more flexible and reusable code by specifying that a generic parameter should be a class constructor. This is particularly useful when you want to work with instances of classes but want to keep the code type safe. You can define a generic type that accepts class constructors and then use that type to create and work with instances of those classes.
function createInstance<T>(
constructor: new (...args: any[]) => T,
...args: any[]
): T {
// Create and return an instance of the specified class
return new constructor(...args);
}Where:
Example 1: In this example, We define the createInstance function, which is a generic factory function. It accepts a class constructor (constructor) and any number of additional arguments (...args). The createInstance function creates an instance of the specified class by invoking the constructor with the provided arguments.
Output: 👁 z25
Example 2: In this example,We define a base class Animal with a name property and a makeSound method. The Dog class extends Animal and adds a breed property and overrides the makeSound method. We create a generic function printAnimalInfo that takes an argument of type T, where T extends the Animal class. This means it can accept instances of Animal or any class that extends it. We create instances of both Animal and Dog. We call the printAnimalInfo function with both instances..
Output: 👁 z43
Reference: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics