Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn TypeScript in Practice | Section
TypeScript for Backend Development

bookTypeScript in Practice

Swipe to show menu

In this chapter, you will combine everything you've learned and apply it in a small, backend-style example.

Defining a Data Structure

First, create a reusable type:

type User = {
  id: number;
  name: string;
  isActive: boolean;
};

Creating Data

Now create an array of users:

let users: User[] = [
  { id: 1, name: "Alice", isActive: true },
  { id: 2, name: "Bob", isActive: false },
];

Writing a Function

Create a function that filters active users:

function getActiveUsers(users: User[]): User[] {
  return users.filter(user => user.isActive);
}

Using a Class

You can also use a class to manage data:

class UserService {
  private users: User[];

  constructor(users: User[]) {
    this.users = users;
  }

  getActiveUsers(): User[] {
    return this.users.filter(user => user.isActive);
  }
}

Running the Code

const service = new UserService(users);
console.log(service.getActiveUsers());

This example shows how TypeScript helps you:

  • Define clear data structures;
  • Safely work with arrays and functions;
  • Organize logic using classes.

These are the same patterns you will use when building backend applications.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 9

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Section 1. Chapter 9
some-alt