TypeScript ConstructorParameters<Type> Utility Type
Last Updated :
22 Jul, 2024
The TypeScript ConstructorParameters<Type> utility type extracts the parameter types from a constructor function Type. It enhances type safety by enabling the creation of instances with correct constructor arguments, ensuring functions use the precise types expected by the constructor.
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: Extracting Constructor Parameters for GFG Class
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: Extracting Constructor Parameters for Rectangle Class
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);
}
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 }