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

bookTypeScript in Practice

Stryg for at vise menuen

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 alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 1. Kapitel 9

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 1. Kapitel 9
some-alt