Course contentsShow
← TypeScript
Lesson 1019 of 1,79624. Classes in TypeScriptFree lesson

Constructor Parameter Types

Type constructor parameters to enforce type safety when creating class instances.

Constructor Parameter Types

What you'll learn: How to enforce type safety when creating new class instances by properly typing constructor parameters.

What This Means

When you create a class in TypeScript, the constructor is where you define what data is required to build an instance. By typing constructor parameters, you tell TypeScript exactly what values must be provided and what types they should be—catching mistakes before your code even runs.

Think of it like an order form: if your "User" class needs a name and age, typing the constructor parameters ensures nobody can create a user without providing those values, or accidentally pass a number where a string belongs.

Basic Constructor Parameter Typing

class User {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

// ✅ Correct usage
const alice = new User("Alice", 30);

// ❌ TypeScript errors
const bob = new User(42, "Bob");        // Wrong order
const charlie = new User("Charlie");    // Missing parameter

TypeScript checks every new User(...) call against the constructor's parameter types, preventing type mismatches and missing arguments.

Why This Matters

Without constructor parameter types, you lose safety at the most critical moment: object creation. You could create instances with malformed data, leading to runtime errors deep in your application. Typed parameters act as a contract—anyone creating your class instances must follow the rules.

Key Takeaway: Type your constructor parameters to enforce type safety at object creation time, catching invalid arguments before they cause runtime errors.