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

bookTypeScript in Practice

Scorri per mostrare il 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.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 9

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 9
some-alt