Data report"State of code review 2024" is now liveRead the full report

TypeScript classes

Kenny DuMez
Kenny DuMez
Graphite software engineer

TypeScript is a strongly-typed superset of JavaScript that adds static types to the language, enabling developers to catch errors at compile-time.

One of the key features of TypeScript is its support for classes. Classes in TypeScript provide a way to create reusable and organized code by encapsulating data and behavior into a single unit. This guide will explore the various aspects of TypeScript classes, including constructors, inheritance, abstract classes, static properties, and more.

A TypeScript class is defined using the class keyword. Here's a basic example:

Terminal
class Person {
name: string
age: number
constructor(name: string, age: number) {
this.name = name
this.age = age
}
greet() {
console.log(
`Hello, my name is ${this.name} and I am ${this.age} years old.`
)
}
}

In this example, we have defined a Person class with two properties (name and age) and a constructor that initializes these properties. We also have a method greet that logs a greeting message.

The constructor is a special method used to initialize objects. It is called automatically when a new instance of the class is created. The constructor can also have parameters to initialize class properties.

Terminal
let person = new Person('Alice', 30)
person.greet() // Output: Hello, my name is Alice and I am 30 years old.

Inheritance allows a class to inherit properties and methods from another class. This is achieved using the extends keyword.

Terminal
class Employee extends Person {
jobTitle: string
constructor(name: string, age: number, jobTitle: string) {
super(name, age)
this.jobTitle = jobTitle
}
describeJob() {
console.log(`I am a ${this.jobTitle}.`)
}
}
let employee = new Employee('Bob', 40, 'Developer')
employee.greet() // Output: Hello, my name is Bob and I am 40 years old.
employee.describeJob() // Output: I am a Developer.

In this example, Employee class inherits from Person class. The super keyword is used to call the constructor of the base class (Person).

An abstract class in TypeScript is a class that cannot be instantiated directly. It is designed to be extended by other classes. Abstract classes can contain abstract methods, which are methods without implementation and must be implemented in derived classes.

Terminal
abstract class Animal {
abstract makeSound(): void
move(): void {
console.log('Moving...')
}
}
class Dog extends Animal {
makeSound() {
console.log('Bark!')
}
}
let dog = new Dog()
dog.makeSound() // Output: Bark!
dog.move() // Output: Moving...

In this example, Animal is an abstract class with an abstract method makeSound. The Dog class extends Animal and provides an implementation for makeSound.

Static members (properties and methods) belong to the class itself rather than to instances of the class. They are defined using the static keyword.

Terminal
class Utility {
static calculateSum(a: number, b: number): number {
return a + b
}
}
console.log(Utility.calculateSum(5, 10)) // Output: 15

Here, calculateSum is a static method of the Utility class and can be called without creating an instance of the class.

TypeScript classes support various access modifiers for properties and methods, including public, private, and protected.

  • public: Accessible from anywhere.
  • private: Accessible only within the class.
  • protected: Accessible within the class and its subclasses.
Terminal
class Vehicle {
public make: string
private model: string
protected year: number
constructor(make: string, model: string, year: number) {
this.make = make
this.model = model
this.year = year
}
getModel() {
return this.model
}
}
class Car extends Vehicle {
constructor(make: string, model: string, year: number) {
super(make, model, year)
}
getYear() {
return this.year
}
}
let car = new Car('Toyota', 'Camry', 2021)
console.log(car.make) // Output: Toyota
console.log(car.getModel()) // Output: Camry
console.log(car.getYear()) // Output: 2021

While classes define a blueprint for creating objects with both properties and methods, interfaces define a contract that classes must adhere to without providing implementations.

Terminal
interface Printable {
print(): void
}
class Document implements Printable {
print() {
console.log('Printing document...')
}
}
let doc = new Document()
doc.print() // Output: Printing document...

Here, Printable is an interface with a single method print. The Document class implements this interface and provides the implementation for the print method.

Classes can be exported from a module to be used in other modules. This is done using the export keyword.

Terminal
// File: Person.ts
export class Person {
constructor(public name: string, public age: number) {}
}
// File: main.ts
import { Person } from './Person'
let person = new Person('Charlie', 25)
console.log(person.name) // Output: Charlie

In this example, the Person class is exported from the Person.ts file and imported in the main.ts file.

For further reading on TypeScript classes, see the official documentation.

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2