0
0
Typescriptprogramming~5 mins

Constructor parameter types in Typescript

Choose your learning style9 modes available
Introduction

Constructor parameter types tell TypeScript what kind of values a class needs when it starts. This helps catch mistakes early and makes your code safer.

When creating a class that needs specific information to work, like a User with a name and age.
When you want to make sure the values passed to a class are the right type, like numbers or strings.
When you want your code editor to help you by showing errors if you pass wrong types.
When you want to clearly show what data a class expects when it is created.
Syntax
Typescript
class ClassName {
  constructor(parameterName: Type) {
    // use parameterName inside the class
  }
}

The constructor is a special method that runs when you create a new object from the class.

Adding : Type after the parameter name tells TypeScript what type to expect.

Examples
This class expects a string called name when you create a new Person.
Typescript
class Person {
  constructor(name: string) {
    console.log(`Hello, ${name}!`);
  }
}
This class expects two numbers, x and y, to create a point.
Typescript
class Point {
  constructor(x: number, y: number) {
    console.log(`Point at (${x}, ${y})`);
  }
}
This class expects an id (number), name (string), and price (number) to create a product.
Typescript
class Product {
  constructor(id: number, name: string, price: number) {
    console.log(`Product: ${name}, Price: $${price}`);
  }
}
Sample Program

This program creates a Car class that needs a make (string) and year (number) when you create it. Then it shows the car details.

Typescript
class Car {
  make: string;
  year: number;

  constructor(make: string, year: number) {
    this.make = make;
    this.year = year;
  }

  display() {
    console.log(`Car: ${this.make}, Year: ${this.year}`);
  }
}

const myCar = new Car("Toyota", 2020);
myCar.display();
OutputSuccess
Important Notes

If you pass the wrong type to the constructor, TypeScript will show an error before running the code.

You can add multiple parameters with different types to the constructor.

Constructor parameters help make your classes clear and safe to use.

Summary

Constructor parameter types tell what kind of values a class needs when created.

They help catch mistakes early by checking types before running the code.

Use them to make your classes clear and easy to understand.