How Do Constructors Work in TypeScript?

Learn How Do Constructors Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Constructors in TypeScript

A constructor in TypeScript is a special method that runs when a new instance of a class is created. It initializes the object's properties and prepares the object for use.

For example, when creating a User object, an application may need to assign an identifier, username, and email address immediately. A constructor allows these values to be provided at creation time instead of assigning them through several separate statements.

TypeScript extends JavaScript constructors with static type checking. Constructor parameters can have explicit types, optional values, default values, and access modifiers. These features make object initialization more predictable and help identify invalid constructor calls during development.

Understanding constructors is important when building classes for application models, services, configuration objects, domain entities, and other structures that require a defined initial state.

1. Understanding the Constructor Syntax

In TypeScript, a constructor is declared using the constructor keyword. It accepts parameters and contains the statements that should execute when an instance is created.

class User {
  name: string;
  age: number;

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

const user = new User("Abhinash", 27);

console.log(user.name);
console.log(user.age);

The constructor receives a string for name and a number for age. It assigns these values to the corresponding instance properties using this.

When JavaScript evaluates new User("Abhinash", 27), it creates a new object and invokes the constructor to initialize that object.

TypeScript checks the argument types. Passing a number where a string is expected produces a compilation error, helping prevent invalid object initialization.

2. Why Constructors Are Useful

Constructors provide a consistent starting point for every instance of a class. Without a constructor, you might need to create an object and then assign its properties separately.

class Product {
  name: string = "";
  price: number = 0;
}

const product = new Product();

product.name = "Keyboard";
product.price = 499;

Although this example works, the object temporarily exists with default values that may not represent a valid product. Another developer might forget to assign the required properties before using the object.

A constructor can require the necessary values when creating the instance:

class Product {
  name: string;
  price: number;

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

const product = new Product("Keyboard", 499);

Now callers must provide both constructor arguments. With strict property initialization enabled, the compiler can also check that the declared properties are initialized appropriately.

Required constructor parameters are useful when an object cannot perform its intended role without certain data. Optional or default parameters should be used when the application genuinely supports creating an instance without every argument.

3. Using Type Annotations in Constructors

Constructor parameters support TypeScript type annotations. These annotations define the values a caller must supply and allow the compiler to check assignments inside the constructor.

class Course {
  title: string;
  duration: number;
  isPublished: boolean;

  constructor(
    title: string,
    duration: number,
    isPublished: boolean
  ) {
    this.title = title;
    this.duration = duration;
    this.isPublished = isPublished;
  }
}

const course = new Course(
  "TypeScript Fundamentals",
  12,
  false
);

This constructor accepts a string, a number, and a boolean. TypeScript checks each argument against its declared parameter type.

For example, supplying a string for duration causes a type error. These checks make it easier to identify incorrect calls before an application is executed.

Type annotations do not validate external values at runtime. When constructor arguments originate from API responses, user input, or untrusted configuration, validate the actual values when runtime guarantees are needed.

4. Constructor Parameter Properties

TypeScript provides a shorthand called parameter properties. By adding an access modifier such as public or private to a constructor parameter, you can declare and initialize a class property directly through that parameter.

class User {
  constructor(
    public name: string,
    public age: number,
    private email: string
  ) {}

  getEmail(): string {
    return this.email;
  }
}

const user = new User(
  "Abhinash",
  27,
  "abhi@example.com"
);

console.log(user.name);
console.log(user.age);
console.log(user.getEmail());

The name and age parameters automatically become public properties. The email parameter becomes a private property that can be accessed from within the class.

The empty constructor body is intentional. TypeScript generates the property initialization behavior for parameter properties during compilation.

This syntax reduces repetitive property declarations and assignments. It is especially convenient for small classes whose constructors mainly store the supplied values.

Use ordinary constructor parameters when a value is needed only during initialization and should not be retained as a property.

5. Default Constructor Parameters

A constructor parameter can have a default value. When a caller omits the argument or supplies undefined, JavaScript uses the default value.

class Course {
  constructor(
    public title: string,
    public duration: number = 10,
    public isPublished: boolean = false
  ) {}
}

const course1 = new Course("TypeScript");
const course2 = new Course("Angular", 15);
const course3 = new Course("React", 8, true);

console.log(course1.duration);     // 10
console.log(course2.duration);     // 15
console.log(course3.isPublished);  // true

The duration parameter defaults to 10, and isPublished defaults to false. Callers can override these defaults when creating an instance.

A parameter with a default value can be omitted when calling the constructor. Required parameters should generally appear before parameters that callers can omit, making the constructor easier to understand.

Default values are suitable when an omitted argument has a meaningful and predictable interpretation, such as a default page size, retry count, or initial status.

6. Optional Constructor Parameters

Optional parameters allow callers to leave out an argument. Add a question mark after the parameter name to indicate that it may be omitted.

class Employee {
  constructor(
    public name: string,
    public department?: string
  ) {}

  getDepartment(): string {
    return this.department ?? "Unassigned";
  }
}

const employee1 = new Employee("Abhinash", "Engineering");
const employee2 = new Employee("Ravi");

console.log(employee1.getDepartment());
console.log(employee2.getDepartment());

The department parameter is optional, so callers can provide only the employee's name. When omitted, the property has the value undefined, and the method uses the nullish coalescing operator to provide a fallback.

Unlike a default parameter, an optional parameter does not automatically assign a non-undefined default value. The property may remain undefined unless the constructor or another method provides a value.

Use optional parameters when the class genuinely supports an absent value. Use default values when an omitted argument should automatically receive a specific value.

7. Readonly Properties in Constructors

The readonly modifier prevents a property from being reassigned after initialization, except through permitted initialization locations such as its declaration or the declaring class's constructor.

class Product {
  readonly id: number;
  name: string;

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

  rename(newName: string): void {
    this.name = newName;
  }
}

const product = new Product(101, "Keyboard");

product.rename("Mechanical Keyboard");

// Compilation error:
// product.id = 202;

The id is assigned during construction and cannot be reassigned through the Product instance after initialization. The name property remains mutable, so the rename method can update it.

You can also declare readonly parameter properties:

class Account {
  constructor(
    public readonly accountId: string,
    public owner: string
  ) {}
}

const account = new Account("ACC-101", "Abhinash");

console.log(account.accountId);
account.owner = "Ravi";

// Compilation error:
// account.accountId = "ACC-202";

Readonly provides a compile-time restriction rather than a complete runtime immutability guarantee. It is useful for identifiers, fixed configuration values, and properties that should remain unchanged through the class's public API.

8. Constructor Overloads

Constructor overloads allow a class to expose multiple valid constructor signatures while providing a single constructor implementation. This is useful when a class supports several ways to create an instance.

class Identifier {
  value: string;

  constructor(value: string);
  constructor(value: number);
  constructor(value: string | number) {
    this.value = String(value);
  }
}

const first = new Identifier("USER-101");
const second = new Identifier(202);

console.log(first.value);
console.log(second.value);

The two overload signatures describe the accepted constructor calls. A caller can supply either a string or a number.

The final constructor implementation accepts the union type string | number and converts the provided value into a string.

Overload signatures do not provide separate runtime implementations. TypeScript uses the signatures to check calls, while JavaScript executes the single implementation.

Overloads are valuable when supported input forms have a clear reason to exist. If parameters can be optional or have meaningful defaults, a simpler constructor may be easier to maintain than multiple overload signatures.

9. Constructor Validation and Initial State

Constructors can perform runtime checks before accepting values into an object's state. Type annotations help validate calls during compilation, but they cannot guarantee that externally supplied data is valid at runtime.

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    if (!Number.isFinite(initialBalance) || initialBalance < 0) {
      throw new Error("Initial balance must be a non-negative number");
    }

    this.balance = initialBalance;
  }

  getBalance(): number {
    return this.balance;
  }
}

const account = new BankAccount(1000);

console.log(account.getBalance());

// Throws an error at runtime:
// const invalidAccount = new BankAccount(-100);

The constructor validates the initial balance before storing it. Negative values, NaN, and infinite values are rejected by the check.

Throwing an error prevents the constructor from successfully returning an instance when its initialization requirements are not satisfied.

This pattern is useful for domain objects that must maintain important rules from the moment they are created. Keep validation focused on the class's responsibilities, and handle errors appropriately at the application boundary.

10. Constructors in Inheritance with super()

When a derived class extends a base class, its constructor can initialize the inherited portion of the object by calling super(). This invokes the base class constructor with the supplied arguments.

class Animal {
  constructor(public name: string) {}
}

class Dog extends Animal {
  constructor(
    name: string,
    public breed: string
  ) {
    super(name);
  }

  getDescription(): string {
    return this.name + " is a " + this.breed;
  }
}

const dog = new Dog("Buddy", "Labrador");

console.log(dog.getDescription());

Animal defines the name property, while Dog adds a breed property. The Dog constructor calls super(name) to initialize the inherited state.

In a derived class constructor, super() must be called before accessing this. The exact arguments depend on the base constructor's parameters.

Use inheritance when the derived class has a genuine relationship with the base class. If classes only need to share an unrelated operation, composition may be a cleaner alternative.

11. Private Constructors and Factory Methods

TypeScript allows a constructor to be declared private. This prevents ordinary external code from creating instances with the new keyword, while methods inside the class can still create instances.

One application is a class that exposes a controlled factory method for creating instances.

class DatabaseConfig {
  private constructor(
    public readonly connectionName: string
  ) {}

  static create(name: string): DatabaseConfig {
    if (name.trim().length === 0) {
      throw new Error("Connection name is required");
    }

    return new DatabaseConfig(name);
  }
}

const config = DatabaseConfig.create("PrimaryDatabase");

console.log(config.connectionName);

// Compilation error:
// const invalid = new DatabaseConfig("PrimaryDatabase");

The private constructor restricts direct instance creation through the class's public API. The static create method validates the input and constructs the instance internally.

This is a factory-method pattern. It is useful when object creation requires controlled setup, validation, or selecting between supported configurations.

A private constructor does not create a singleton automatically. If a class must return the same instance every time, the factory must also explicitly manage and reuse that instance.

12. Understanding Constructors and Strict Property Initialization

TypeScript's strict property initialization checking is designed to catch class properties that may remain uninitialized when an instance is created. When enabled through strictPropertyInitialization, required properties must be initialized in their declarations or constructor, or otherwise be marked with the definite assignment assertion when initialization occurs through a process the compiler cannot verify.

class User {
  name: string;
  age: number;

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

This constructor initializes both required properties, allowing the compiler to verify that a new User instance receives the necessary state.

A property initializer can also provide an initial value:

class Settings {
  theme: string = "light";
  fontSize: number = 16;

  constructor(theme?: string, fontSize?: number) {
    if (theme !== undefined) {
      this.theme = theme;
    }

    if (fontSize !== undefined) {
      this.fontSize = fontSize;
    }
  }
}

const settings = new Settings("dark", 18);

The property declarations initialize the default state, while the constructor replaces those defaults when arguments are provided. This can make a class easier to use when it supports a sensible default configuration.

Avoid using the definite assignment assertion operator simply to silence compiler errors. Use it only when another initialization mechanism genuinely guarantees that the property will be assigned before it is read.

13. Common Constructor Mistakes to Avoid

  • Forgetting to initialize required properties: with strict property initialization enabled, ensure every required property is initialized by a declaration or constructor.
  • Confusing optional parameters with default parameters: an optional parameter may remain undefined, while a default parameter receives its configured value when omitted or explicitly passed undefined.
  • Adding a return type to the constructor: constructors do not declare an ordinary return type like methods do.
  • Expecting overloads to provide multiple implementations: overload signatures only describe valid calls; one implementation handles the actual construction process.
  • Forgetting super() in a derived class: a derived constructor must call super before using this.
  • Skipping runtime validation: TypeScript annotations do not guarantee that untrusted input satisfies the expected constraints.
  • Making constructors unnecessarily complicated: move unrelated operations into dedicated methods or services instead of placing every responsibility inside the constructor.

14. Best Practices for TypeScript Constructors

  • Require essential values through constructor parameters so instances begin in a valid state.
  • Use explicit parameter types when they clarify the class's creation requirements.
  • Use parameter properties to reduce boilerplate when constructor arguments directly initialize properties.
  • Choose optional parameters for genuinely optional values and defaults for predictable initial values.
  • Use readonly for properties that should not be reassigned after initialization through ordinary TypeScript code.
  • Validate runtime inputs when the class must enforce domain rules or handle untrusted values.
  • Keep constructor logic focused on initialization rather than long-running operations or unrelated application workflows.
  • Use constructor overloads only when multiple creation signatures improve the public API.
  • Call super correctly in derived classes and initialize inherited state consistently.

Conclusion

Constructors are an essential part of TypeScript classes because they establish an object's initial state. They allow developers to provide required values, define defaults, initialize readonly fields, validate input, and control how instances are created.

Features such as parameter properties, constructor overloads, private constructors, and inheritance with super() make it possible to support different initialization requirements while retaining type safety.

By keeping constructors focused, initializing required properties consistently, and separating compile-time checks from runtime validation, you can design classes that are more predictable, maintainable, and reliable.

Code Examples

Create a Class with a Constructor

typescript
class User {
  name: string;
  age: number;

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

const user = new User("Abhinash", 27);

console.log(user.name);
console.log(user.age);
    

Use Constructor Parameter Properties

typescript
class Product {
  constructor(
    public readonly id: number,
    public name: string,
    public price: number
  ) {}

  updatePrice(newPrice: number): void {
    this.price = newPrice;
  }
}

const product = new Product(101, "Keyboard", 499);

product.updatePrice(599);

console.log(product.id);
console.log(product.name);
console.log(product.price);
    

Use Default and Optional Parameters

typescript
class Course {
  constructor(
    public title: string,
    public duration: number = 10,
    public instructor?: string
  ) {}
}

const first = new Course("TypeScript");
const second = new Course("Angular", 15, "Abhinash");

console.log(first.duration);       // 10
console.log(first.instructor);     // undefined
console.log(second.instructor);    // Abhinash
    

Create Constructor Overloads

typescript
class Identifier {
  value: string;

  constructor(value: string);
  constructor(value: number);
  constructor(value: string | number) {
    this.value = String(value);
  }
}

const first = new Identifier("USER-101");
const second = new Identifier(202);

console.log(first.value);
console.log(second.value);
    

Validate Values During Construction

typescript
class BankAccount {
  constructor(
    public readonly accountId: string,
    private balance: number
  ) {
    if (
      accountId.trim().length === 0 ||
      !Number.isFinite(balance) ||
      balance < 0
    ) {
      throw new Error("Invalid account details");
    }
  }

  getBalance(): number {
    return this.balance;
  }
}

const account = new BankAccount("ACC-101", 1000);

console.log(account.getBalance());
    

Initialize a Derived Class with super()

typescript
class Animal {
  constructor(public name: string) {}
}

class Dog extends Animal {
  constructor(
    name: string,
    public breed: string
  ) {
    super(name);
  }

  getDescription(): string {
    return this.name + " is a " + this.breed;
  }
}

const dog = new Dog("Buddy", "Labrador");

console.log(dog.getDescription());
    

Pro Tip

Use constructors to establish the minimum valid state required by an object. Prefer parameter properties when they improve readability, default parameters for meaningful initial values, and runtime validation when business rules must be enforced. A TypeScript constructor checks types at compile time, but it does not automatically validate external data.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.