Imagine planning a vacation. You know where you want to go, when you want to leave, and who you’re traveling with. But the process of finding the right flights, comparing prices, and selecting seats can be overwhelming. This is where a well-designed flight booking system comes in. In this tutorial, we’ll build a simplified, interactive flight booking system using TypeScript. We’ll focus on the core functionalities: searching for flights, displaying flight details, and simulating the booking process. This project will not only teach you fundamental TypeScript concepts but also demonstrate how to structure a more complex application.
Why TypeScript for a Flight Booking System?
TypeScript, a superset of JavaScript, adds static typing. This means you define the data types for your variables, function parameters, and return values. Why is this beneficial?
- Early Error Detection: TypeScript catches errors during development, before runtime. This saves time and frustration.
- Improved Code Readability: Types make your code self-documenting, making it easier to understand and maintain.
- Enhanced Developer Experience: IDEs provide better autocompletion, refactoring, and navigation, leading to increased productivity.
- Scalability: As your project grows, TypeScript’s type system helps manage complexity.
For a flight booking system, where data integrity is crucial (flight numbers, dates, passenger details), TypeScript’s type safety is a significant advantage.
Setting Up Your TypeScript Environment
Before we start, you’ll need Node.js and npm (Node Package Manager) installed. Most modern IDEs (like VS Code) have excellent TypeScript support. Here’s how to set up your project:
- Create a Project Directory: Create a new folder for your project (e.g., `flight-booking-system`).
- Initialize npm: Open your terminal, navigate to your project directory, and run `npm init -y`. This creates a `package.json` file.
- Install TypeScript: Run `npm install typescript –save-dev`. This installs TypeScript as a development dependency.
- Create a `tsconfig.json` file: Run `npx tsc –init`. This creates a configuration file that tells TypeScript how to compile your code. You can customize this file to suit your needs (e.g., specifying the output directory, target ECMAScript version). For this tutorial, the default settings will work.
- Create a TypeScript file: Create a file named `index.ts` in your project directory. This is where we’ll write our code.
Core Concepts: Data Structures and Types
Let’s define the fundamental data structures for our flight booking system. We’ll use interfaces and types to represent data.
1. Flight Interface
This interface describes the properties of a flight.
interface Flight {
flightNumber: string;
origin: string;
destination: string;
departureTime: string; // Consider using Date objects in a real-world scenario
arrivalTime: string; // Consider using Date objects in a real-world scenario
price: number;
availableSeats: number;
}
Explanation:
- `flightNumber`: A unique identifier for the flight (e.g., “UA123”).
- `origin`: The departure airport code (e.g., “JFK”).
- `destination`: The arrival airport code (e.g., “LAX”).
- `departureTime`, `arrivalTime`: Departure and arrival times (represented as strings for simplicity). In a production system, you’d likely use the `Date` object.
- `price`: The flight price.
- `availableSeats`: The number of available seats.
2. Passenger Type
This type defines the structure for passenger information.
type Passenger = {
firstName: string;
lastName: string;
dateOfBirth: string; // Consider using Date objects in a real-world scenario
passportNumber: string;
};
Explanation:
- `firstName`, `lastName`: Passenger’s first and last names.
- `dateOfBirth`: Passenger’s date of birth (represented as a string for simplicity).
- `passportNumber`: Passenger’s passport number.
3. Booking Type
This type represents a booking.
type Booking = {
flight: Flight;
passengers: Passenger[];
bookingDate: string; // Consider using Date objects in a real-world scenario
bookingReference: string;
};
Explanation:
- `flight`: A `Flight` object representing the booked flight.
- `passengers`: An array of `Passenger` objects.
- `bookingDate`: The booking date (represented as a string for simplicity).
- `bookingReference`: A unique booking reference number.
Implementing Flight Search
Let’s create a function to simulate searching for flights. We’ll use a hardcoded array of flights for this example.
// Sample flight data (replace with a database or API call in a real application)
const flights: Flight[] = [
{
flightNumber: "UA123",
origin: "JFK",
destination: "LAX",
departureTime: "08:00",
arrivalTime: "11:00",
price: 300,
availableSeats: 50,
},
{
flightNumber: "AA456",
origin: "JFK",
destination: "LAX",
departureTime: "10:00",
arrivalTime: "13:00",
price: 350,
availableSeats: 25,
},
{
flightNumber: "DL789",
origin: "SFO",
destination: "ORD",
departureTime: "14:00",
arrivalTime: "20:00",
price: 400,
availableSeats: 75,
},
];
function searchFlights(
origin: string,
destination: string,
departureDate?: string // Optional parameter
): Flight[] {
const results: Flight[] = flights.filter(
(flight) => flight.origin === origin && flight.destination === destination
);
// Filter by departure date if provided (simplified)
if (departureDate) {
// In a real application, you would parse the date string and compare Date objects.
const formattedDepartureDate = departureDate.replace(/-/g, "/"); // Handle date format differences
return results.filter(flight => flight.departureTime.startsWith(formattedDepartureDate)); // Simple date comparison
}
return results;
}
// Example usage
const searchResults = searchFlights("JFK", "LAX");
console.log("Search Results:", searchResults);
const searchResultsWithDate = searchFlights("JFK", "LAX", "2024-12");
console.log("Search Results (with date):
