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

bookTypeScript in Practice

Svep för att visa menyn

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.

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 9

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 9
some-alt