TypeScript ยท Chapter 23 of 44

TypeScript Classes

TypeScript classes work like JavaScript classes but let you add type annotations to properties, constructor parameters, and methods. This ensures class instances always have the correct shape and behavior.

A class defines properties (fields) and methods (functions), and the `constructor` method runs automatically when a new instance is created with the `new` keyword.

Syntax
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

Defining a class

A class declares its properties with types, and a constructor to initialize them. Methods are defined like regular functions but without the `function` keyword, inside the class body.

Creating instances

You create a new object from a class using the `new` keyword, which runs the constructor and returns an object with access to all the class's properties and methods.

Example 1 (typescript)
class Person {
  name: string;
  age: number;

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

  greet(): string {
    return `Hi, I am ${this.name}`;
  }
}
const p = new Person("Ana", 30);
console.log(p.greet());
Output
Hi, I am Ana

The constructor sets initial property values, and greet() is a method that uses `this` to access them.

Example 2 (typescript)
class Counter {
  count: number = 0;

  increment(): void {
    this.count++;
  }
}
const c = new Counter();
c.increment();
c.increment();
console.log(c.count);
Output
2

count starts at 0 and is updated each time increment() is called on the instance.

Key points

  • Classes group related properties and methods together.
  • The constructor runs automatically when creating a new instance.
  • `this` refers to the current instance inside methods.
  • Properties and method parameters can be typed just like variables.
๐Ÿ’ก Note: TypeScript classes compile down to standard JavaScript classes, with all type annotations removed.

๐Ÿ“ Quick Quiz

1. Which keyword creates a new instance of a class?

2. What does the constructor do?

3. What does `this` refer to inside a class method?