Open In App

TypeScript ConstructorParameters<Type> Utility Type

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The TypeScript ConstructorParameters<Type> utility type extracts parameter types from a constructor function Type. It helps define functions that create instances of classes with correct constructor arguments, and It allows you to access and use the types of constructor function parameters. enhancing type safety.

Syntax

type ConstructorParametersType = ConstructorParameters<Type>;

Parameters:

  • ConstructorParametersType: The name of the type that represents the parameter types of the constructor function.
  • Type: The constructor function type from which you want to extract the parameter types.

Example 1 In this example, we define a class GFG with a constructor that accepts two string parameters. Using ConstructorParameters<typeof GFG>, we extract these parameter types. We then create a createGFG function that utilizes these types to instantiate GFG objects with varying parameter values.

Javascript




// Define a class and its constructor
class GFG {
    constructor(name: string, course: string) {
        this.name = name;
        this.course = course;
    }
    name: string;
    course: string;
}
  
// Extract parameter types of the constructor
type GFGConstructorParams = ConstructorParameters<typeof GFG>;
  
// Create a function that creates an instance of the class
function createGFG(...params: GFGConstructorParams): GFG {
    return new GFG(...params);
}
  
const GFG1 = createGFG("GeeksforGeeks", "Java");
const GFG2 = createGFG("gfg", "Python");
  
console.log(GFG1);
console.log(GFG2);


Output:

GFG { name: 'GeeksforGeeks', course: 'Java' }
GFG { name: 'gfg', course: 'Python' }

Example 2: In this example, we create a Rectangle class with a constructor accepting two numbers: width and height. By using ConstructorParameters<typeof Rectangle>, we obtain the parameter types [number, number]. We then craft a createRectangle function using these types to generate Rectangle instances with distinct dimensions.

Javascript




// Define a class and its constructor
class Rectangle {
    constructor(public width: number, public height: number) { }
}
  
// Extract parameter types of the constructor
type RectangleConstructorParams =
    ConstructorParameters<typeof Rectangle>;
  
// Create a function that creates an instance of the class
function createRectangle(...params: RectangleConstructorParams):
    Rectangle {
    return new Rectangle(...params);
}
  
// Example usage
const rect1 = createRectangle(5, 10);
const rect2 = createRectangle(8, 6);
  
console.log(rect1);
console.log(rect2);


Output:

Rectangle { width: 5, height: 10 }
Rectangle { width: 8, height: 6 }

Reference:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads