0
0
Typescriptprogramming~20 mins

ConstructorParameters type in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the ConstructorParameters Type in TypeScript
📖 Scenario: You are building a simple system to manage books in a library. Each book has a title and an author. You want to create a class for books and then use TypeScript's ConstructorParameters type to extract the types of the constructor parameters for reuse.
🎯 Goal: Learn how to use the ConstructorParameters utility type to get the types of a class constructor's parameters and use them to type a function parameter.
📋 What You'll Learn
Create a Book class with a constructor that takes title and author as strings
Create a type alias BookParams using ConstructorParameters for the Book class
Write a function createBook that takes BookParams as its parameter and returns a new Book instance
Print the created book's title and author
💡 Why This Matters
🌍 Real World
Extracting constructor parameter types helps when you want to reuse those types elsewhere, like in factory functions or dependency injection.
💼 Career
Understanding TypeScript utility types like <code>ConstructorParameters</code> is useful for writing clean, type-safe code in professional TypeScript projects.
Progress0 / 4 steps
1
Create the Book class
Create a class called Book with a constructor that takes two parameters: title and author, both of type string. Store these parameters as public properties.
Typescript
Need a hint?

Use constructor(public title: string, public author: string) {} to create and store the properties.

2
Create the BookParams type alias
Create a type alias called BookParams that uses ConstructorParameters with the typeof Book to get the constructor parameter types.
Typescript
Need a hint?

Use type BookParams = ConstructorParameters; to extract the constructor parameters.

3
Write the createBook function
Write a function called createBook that takes one parameter named params of type BookParams. The function should return a new Book instance using the spread operator to pass params to the Book constructor.
Typescript
Need a hint?

Use return new Book(...params); inside the function to create the book.

4
Create a book and print its details
Call the createBook function with the parameters "The Hobbit" and "J.R.R. Tolkien". Store the result in a variable called myBook. Then print the book's title and author using console.log.
Typescript
Need a hint?

Use console.log(`Title: ${myBook.title}, Author: ${myBook.author}`); to print the details.