Open In App

TypeScript Construct Signatures

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript Construct Signatures define the shape of a constructor function, specifying the parameters it expects and the type of object it constructs. They use the new keyword in a type declaration to ensure the correct instantiation of classes or objects.

Syntax

type Constructor = new (param1: Type1, param2: Type2, ...) => ReturnType;

Parameters

  • Constructor: This is the name you give to the type that represents the constructor function.
  • new: The new keyword indicates that this is a construct signature for creating new instances.
  • ( and ): These parentheses enclose the parameter list for the constructor function.
  • param1, param2, ...: These are the names of the parameters that the constructor function expects when creating instances. Each parameter is followed by a colon and its respective type (e.g., Type1, Type2, ...).

ReturnType

This is the type of object that the constructor function constructs and returns when called with the new operator.

Example 1: Class with Constructor

In this example, a TypeScript class Person has a constructor that takes a name parameter to set the instance's name property. The greet method logs a greeting message. An instance is created with "GeeksforGeeks".

JavaScript
// Define a class with a constructor
class Person {
	name: string;
	constructor(name: string) {
		this.name = name;
	}
	greet() {
		console.log(`Hello, my name is ${this.name}`);
	}
}

// Create an instance of the class 
// using the constructor
const person = new Person("GeeksforGeeks");

// Call the function (method) on the instance
person.greet();

Output:

Hello, my name is GeeksforGeeks

Example 2: Function Creating Instances

In this example, we have created a constructor in a class named book and for creating an objcet of that book class we are calling a function createBook and passing the needed parameters and it returns a new object of Book.

JavaScript
// Define a class for 
// representing books
class Book {
	constructor(
		public title: string, public author: string) { }
}

// Define a construct
// signature for the Book class
type BookConstructor = 
	new (title: string, author: string) => Book;

// Create a factory function based
// on the construct signature
function createBook(BookConstructor: BookConstructor,
	title: string, author: string) {
	return new BookConstructor(title, author);
}

// Use the factory function 
// to create a book instance
const bookInstance = createBook(Book,
	"The Story of My Experiments", "Mahatma Gandhi");

// Log the book's properties
console.log("Title:", bookInstance.title);
console.log("Author:", bookInstance.author);

Output:

Title: The Story of My Experiments
Author: Mahatma Gandhi

Next Article

Similar Reads