Open In App

TypeScript Using Class Types in Generics

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.

Syntax

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.






// Define a generic factory function
function createInstance<T>(constructor:
    new (...args: any[]) => T, ...args: any[]): T {
    return new constructor(...args);
}
  
// Example classes
class Product {
    constructor(
        public name: string, 
        public price: number) { }
}
  
class Person {
    constructor(
        public name: string, 
        public age: number) { }
}
  
// Create instances using the factory function
const laptop = 
    createInstance(Product, 'Laptop', 999);
console.log(laptop);
  
const user = 
    createInstance(Person, 'GeeksforGeeks', 30);
console.log(user);

Output:

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




class Animal {
    constructor(public name: string) { }
    makeSound(): string {
        return "Some generic animal sound";
    }
}
  
class Dog extends Animal {
    constructor(name: string, public breed: string) {
        super(name);
    }
  
    makeSound(): string {
        return "Woof! Woof!";
    }
}
  
function printAnimalInfo<T extends Animal>
    (animal: T): void {
        console.log(`Name: ${animal.name}`);
        console.log(`Sound: ${animal.makeSound()}`);
}
  
// Create instances of Animal and Dog
const genericAnimal = new Animal("Generic Animal");
const myDog = new Dog("Buddy", "Golden Retriever");
  
// Use the generic function with 
// instances of different classes
printAnimalInfo(genericAnimal);
printAnimalInfo(myDog);

Output:

Reference: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics


Article Tags :