TypeScript 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.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
TypeScript in Practice
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.
Thanks for your feedback!