Skip to content
Share
Explore

The TypeScript Bookstore

This lab creates a TypeScript Application to run the run the Business Domain of a Book store.
By the time you have completed this Lab, you will have:
Learned how to program directly in TypeScript.
Learned how run your TypeScript Program directly at the Command Line.
Your Program Hand In is going to be to send me the URL of your Project on - Here in this Lab you will learn how to do npm -publish to make your project available to the World on NPMjs.com. (You will have a live URL you can put in Resume and LINKEDIN). Next week we will see how to make a README markdown formatted document to present your project and business domain in the polished, visually appealing way.

This Document contains a template document you can replicate to do your own Project.

See also:

megaphone
Here I will create a TypeScript application modeling a bookstore with several classes, demonstrating shared field composition and object interaction via method calls.
I'll provide you with two UML diagrams:
a Class Diagram showing the structure of the classes and their relationships, and
a Sequence Diagram illustrating the object interactions.

1. Class Diagram:

image.png

Explanation: - The Bookstore class has composition relationships (filled diamond) with Book, Customer, and Order. - The Order class has an association with Customer and a composition relationship with Book. - All classes have their respective attributes and methods listed.
2. Sequence Diagram:
image.png
Explanation: (This is your ‘use cases’)
- The sequence starts with creating a Bookstore instance.
- Books and Customers are added to the Bookstore.
- An Order is created for a Customer.
- Books are added to the Order, which updates the Book's stock.
- Finally, displayInfo() methods are called to show the state of various objects.

These diagrams provide a visual representation of the class structure and object interactions in the bookstore application. The Class Diagram shows the static structure and relationships between classes, while the Sequence Diagram illustrates the dynamic interactions between objects over time.

info
I'll include detailed explanatory comments to help students understand the code structure and concepts.
Here's a TypeScript application that models a bookstore:
error
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"lib": ["es2015", "dom"],
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./",
"declaration": true
},
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules"
]
}


// bookstore.ts : One File into which goes all of my Code

class Book {
constructor(
public id: string,
public title: string,
public author: string,
public price: number,
public stock: number
) {}

displayInfo(): void {
console.log(`${this.title} by ${this.author} - $${this.price} (${this.stock} in stock)`);
}
}

class Customer {
constructor(
public id: string,
public name: string,
public email: string
) {}

displayInfo(): void {
console.log(`Customer: ${this.name} (${this.email})`);
}
}

class Order {
private _books: { book: Book; quantity: number }[] = [];
private _totalPrice: number = 0;

constructor(
public id: string,
public customer: Customer
) {}

addBook(book: Book, quantity: number): void {
if (book.stock >= quantity) {
let existingBookIndex = -1;
for (let i = 0; i < this._books.length; i++) {
if (this._books[i].book.id === book.id) {
existingBookIndex = i;
break;
}
}
if (existingBookIndex !== -1) {
this._books[existingBookIndex].quantity += quantity;
} else {
this._books.push({ book, quantity });
}
this._totalPrice += book.price * quantity;
book.stock -= quantity;
} else {
throw new Error("Not enough stock");
}
}

displayInfo(): void {
console.log(`Order ${this.id} for:`);
this.customer.displayInfo();
console.log("Books ordered:");
this._books.forEach(({ book, quantity }) => {
console.log(` ${quantity}x ${book.title}`);
});
console.log(`Total Price: $${this._totalPrice.toFixed(2)}`);
}
}

class Bookstore {
private _inventory: Book[] = [];
private _customers: Customer[] = [];
private _orders: Order[] = [];

constructor(public name: string) {}

addBook(book: Book): void {
this._inventory.push(book);
}

addCustomer(customer: Customer): void {
this._customers.push(customer);
}

createOrder(customer: Customer): Order {
const order = new Order(`ORD-${this._orders.length + 1}`, customer);
this._orders.push(order);
return order;
}

displayInfo(): void {
console.log(`Welcome to ${this.name}!`);
console.log(`We have ${this._inventory.length} books in stock.`);
console.log(`We have served ${this._customers.length} customers.`);
console.log(`We have processed ${this._orders.length} orders.`);
}
}

// Main application logic
const myBookstore = new Bookstore("TypeScript Bookstore");

const book1 = new Book("B001", "TypeScript in Action", "John Doe", 29.99, 50);
const book2 = new Book("B002", "Node.js Essentials", "Jane Smith", 24.99, 30);
myBookstore.addBook(book1);
myBookstore.addBook(book2);

const customer1 = new Customer("C001", "Alice Johnson", "alice@example.com");
const customer2 = new Customer("C002", "Bob Williams", "bob@example.com");
myBookstore.addCustomer(customer1);
myBookstore.addCustomer(customer2);

const order1 = myBookstore.createOrder(customer1);
order1.addBook(book1, 2);
order1.addBook(book2, 1);

const order2 = myBookstore.createOrder(customer2);
order2.addBook(book2, 3);

console.log("Bookstore Information:");
myBookstore.displayInfo();

console.log("\nOrder Information:");
order1.displayInfo();
console.log();
order2.displayInfo();

console.log("\nUpdated Book Stock:");
book1.displayInfo();
book2.displayInfo();

This TypeScript application models a bookstore with the following classes:
1. `Book`: Represents a book in the inventory.
2. `Customer`: Represents a customer of the bookstore.
3. `Order`: Represents an order placed by a customer.
4. `Bookstore`: Manages the overall bookstore operations.

The application demonstrates:
- Shared field composition:
The `Bookstore` class contains arrays of `Book`, `Customer`, and `Order` objects.
- Object interaction via method calls:
Methods like `addBook`, `createOrder`, and `displayInfo` show how objects interact.
- Encapsulation: Private fields with getter and setter methods.
- Type safety: TypeScript's static typing helps prevent errors.

To use this code in Visual Studio Code:

1. Create a new directory for your project.
2. Open the directory in Visual Studio Code.
3. Create a new file named `bookstore.ts`.
Want to print your doc?
This is not the way.
Try clicking the ··· in the right corner or using a keyboard shortcut (
CtrlP
) instead.