TypeScript is a strongly-typed superset of JavaScript that adds static types to the language, enabling developers to catch errors at compile-time.
What are classes in TypeScript?
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.
Basic structure of a TypeScript class
A TypeScript class is defined using the class
keyword. Here's a basic example:
class Person {name: stringage: numberconstructor(name: string, age: number) {this.name = namethis.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.
TypeScript class constructor
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.
let person = new Person('Alice', 30)person.greet() // Output: Hello, my name is Alice and I am 30 years old.
TypeScript class inheritance
Inheritance allows a class to inherit properties and methods from another class. This is achieved using the extends
keyword.
class Employee extends Person {jobTitle: stringconstructor(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
).
TypeScript abstract class
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.
abstract class Animal {abstract makeSound(): voidmove(): 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
.
TypeScript static class members
Static members (properties and methods) belong to the class itself rather than to instances of the class. They are defined using the static
keyword.
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 class property modifiers
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.
class Vehicle {public make: stringprivate model: stringprotected year: numberconstructor(make: string, model: string, year: number) {this.make = makethis.model = modelthis.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: Toyotaconsole.log(car.getModel()) // Output: Camryconsole.log(car.getYear()) // Output: 2021
TypeScript class vs interface
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.
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.
TypeScript export class
Classes can be exported from a module to be used in other modules. This is done using the export
keyword.
// File: Person.tsexport class Person {constructor(public name: string, public age: number) {}}// File: main.tsimport { 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.