TYPESCRIPT
TypeScript Class: Syntax, Usage, and Examples
A TypeScript class defines a blueprint for creating objects with properties and methods. It allows you to encapsulate data, enforce structure, and implement object-oriented programming concepts like inheritance, polymorphism, and encapsulation. You can use classes to organize code, enforce consistency, and make your applications more scalable.
How to Use Classes in TypeScript
A basic class in TypeScript consists of properties, a constructor, and methods. You define a class using the class
keyword, followed by the class name.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
introduce(): void {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
const person1 = new Person("Alice", 30);
person1.introduce(); // Output: Hi, I'm Alice and I'm 30 years old.
- The
constructor
method initializes an object with values when you create an instance. - Properties like
name
andage
store object data. - The
introduce
method defines behavior for the class.
When to Use Classes in TypeScript
Organizing Code into Reusable Components
Classes help you bundle related properties and methods together. Instead of writing repetitive logic, you can define a class once and reuse it throughout your application.
class Product {
constructor(public name: string, public price: number) {}
display(): void {
console.log(`${this.name} costs $${this.price}`);
}
}
const book = new Product("TypeScript Guide", 25);
book.display(); // Output: TypeScript Guide costs $25
Implementing Inheritance
You can extend an existing class to share and customize behavior using the extends
keyword.
class Animal {
move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
bark(): void {
console.log("Woof!");
}
}
const myDog = new Dog();
myDog.move(); // Output: Moving...
myDog.bark(); // Output: Woof!
Defining Models for APIs and Databases
If you're working with APIs or databases, you can use classes to define data models with strict typing.
class UserModel {
constructor(public id: number, public username: string, public email: string) {}
}
const user = new UserModel(1, "john_doe", "john@example.com");
console.log(user.username); // Output: john_doe
Examples of Classes in TypeScript
Using Static Properties and Methods
Static properties and methods belong to the class itself rather than an instance. You can use them to store constants or utility functions.
class MathHelper {
static PI: number = 3.14;
static square(num: number): number {
return num * num;
}
}
console.log(MathHelper.PI); // Output: 3.14
console.log(MathHelper.square(5)); // Output: 25
Abstract Classes
An abstract class serves as a blueprint for other classes. It cannot be instantiated directly but forces child classes to implement specific methods.
abstract class Vehicle {
abstract drive(): void;
}
class Car extends Vehicle {
drive(): void {
console.log("Car is driving.");
}
}
const myCar = new Car();
myCar.drive(); // Output: Car is driving.
Implementing Multiple Behaviors with Interfaces
You cannot extend multiple classes in TypeScript, but you can implement multiple interfaces to achieve similar functionality.
interface Logger {
log(message: string): void;
}
interface Calculator {
calculate(a: number, b: number): number;
}
class FinanceApp implements Logger, Calculator {
log(message: string): void {
console.log(`Log: ${message}`);
}
calculate(a: number, b: number): number {
return a + b;
}
}
const app = new FinanceApp();
app.log("Transaction successful."); // Output: Log: Transaction successful.
console.log(app.calculate(10, 20)); // Output: 30
Readonly Properties
Use readonly
when you want to prevent modifications to a property after initialization.
class Config {
readonly apiKey: string = "12345-ABCDE";
}
const settings = new Config();
console.log(settings.apiKey); // Output: 12345-ABCDE
// settings.apiKey = "67890"; // Error: Cannot assign to 'apiKey' because it is a read-only property.
Learn More About Classes in TypeScript
Difference Between Class and Interface
A class defines structure and behavior, whereas an interface only defines structure.
interface Person {
name: string;
speak(): void;
}
class Student implements Person {
constructor(public name: string) {}
speak(): void {
console.log(`Hello, I'm ${this.name}`);
}
}
Exporting and Importing Classes
You can split your code into multiple files using export
and import
.
File: Car.ts
export class Car {
constructor(public brand: string) {}
drive(): void {
console.log(`${this.brand} is driving.`);
}
}
File: main.ts
import { Car } from "./Car";
const myCar = new Car("Toyota");
myCar.drive(); // Output: Toyota is driving.
Static Class and Methods
A static class cannot be instantiated. Instead, all its methods and properties belong to the class itself.
class Utility {
static greet(): void {
console.log("Hello, world!");
}
}
Utility.greet(); // Output: Hello, world!
Class Decorators
A class decorator modifies a class at runtime.
function logClass(target: Function) {
console.log(`Class ${target.name} was created.`);
}
@logClass
class Account {
constructor(public balance: number) {}
}
Extending Multiple Classes
You can't extend multiple classes in TypeScript, but you can combine them using mixins.
class Runner {
run(): void {
console.log("Running...");
}
}
class Swimmer {
swim(): void {
console.log("Swimming...");
}
}
class Athlete implements Runner, Swimmer {
run!: () => void;
swim!: () => void;
}
Object.assign(Athlete.prototype, Runner.prototype, Swimmer.prototype);
const athlete = new Athlete();
athlete.run(); // Output: Running...
athlete.swim(); // Output: Swimming...
Method Overriding in Classes
A subclass can override a method from its parent using super
.
class Parent {
greet(): void {
console.log("Hello from the parent class.");
}
}
class Child extends Parent {
greet(): void {
super.greet();
console.log("Hello from the child class.");
}
}
const child = new Child();
child.greet();
// Output:
// Hello from the parent class.
// Hello from the child class.
A TypeScript class provides structure and behavior for objects. It allows you to encapsulate data, create reusable components, and enforce consistency. You can extend classes, use abstract classes, implement interfaces, and define static properties to build maintainable applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.