Open In App

TypeScript InstanceType<Type> Utility Type

In this article, we are going to learn about InstanceType<Type> Utility Type in Typescript. TypeScript is a popular programming language used for building scalable and robust applications. In TypeScript, the InstanceType<Type> utility type is used to extract the instance type of a constructor function or class type. It allows you to infer the type of instances that can be created from a constructor or class.

Syntax

type T1 = InstanceType<Type>;

Parameters

Example 1

In this example,






class Person {
    constructor(public name: string, public age: number) { }
}
  
type PersonInstance = InstanceType<typeof Person>;
  
const person: PersonInstance = new Person("Alice", 30);
  
console.log(person.name); // "Alice"
console.log(person.age); // 30

Output

Example 2

In this example,






class Product {
    constructor(public name: string, public price: number) { }
}
  
class ShoppingCart {
    private items: InstanceType<typeof Product>[] = [];
  
    addItem(product: InstanceType<typeof Product>): void {
        this.items.push(product);
    }
  
    getTotalPrice(): number {
        return this.items.reduce((total, product
                ) => total + product.price, 0);
    }
}
  
// Create instances of Product
const laptop = new Product("Laptop", 1000);
const smartphone = new Product("Smartphone", 500);
  
// Create an instance of ShoppingCart
const cart = new ShoppingCart();
  
// Add products to the cart
cart.addItem(laptop);
cart.addItem(smartphone);
  
// Get the total price of the items in the cart
const totalPrice = cart.getTotalPrice();
  
// Output: Total Price: $1500
console.log(`Total Price: $${totalPrice}`);

Output

Reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#instancetypetype


Article Tags :