Building an Address Book Application in TypeScript
- Published on
- • 3 mins read•––– views
Unleash Your Inner Code Ninja 🥋
In this tutorial, we will build a simple Address Book Application using TypeScript. We'll create two classes, Contact and AddressBook, to manage contacts and their information.
Class Diagram
Let's start by visualizing the class diagram for our Address Book Application:
In our class diagram, we have two main classes:
AddressBook
: This class represents the address book itself and contains an array ofContact
objects.Contact
: This class represents individual contacts and stores their name, email, and phone number.
TypeScript Code
Now, let's implement these classes in TypeScript.
// Contact.ts
class Contact {
private name: string;
private email: string;
private phone: string;
constructor(name: string, email: string, phone: string) {
this.name = name;
this.email = email;
this.phone = phone;
}
// Getter methods
getName(): string {
return this.name;
}
getEmail(): string {
return this.email;
}
getPhone(): string {
return this.phone;
}
}
// AddressBook.ts
class AddressBook {
private contacts: Contact[];
constructor() {
this.contacts = [];
}
// Add a contact to the address book
addContact(contact: Contact): void {
this.contacts.push(contact);
}
// Get all contacts in the address book
getAllContacts(): Contact[] {
return this.contacts;
}
}
In the Contact class, we define private properties for name, email, and phone, and provide getter methods to access these properties. The AddressBook class maintains an array of Contact objects and provides methods to add contacts and retrieve all contacts.
Using the Address Book
Now that we have our classes defined, let's see how we can use the Address Book Application:
// Creating an address book
const myAddressBook = new AddressBook();
// Adding contacts
const contact1 = new Contact("John Doe", "[email protected]", "123-456-7890");
const contact2 = new Contact("Jane Smith", "[email protected]", "987-654-3210");
myAddressBook.addContact(contact1);
myAddressBook.addContact(contact2);
// Retrieving all contacts
const allContacts = myAddressBook.getAllContacts();
console.log("All Contacts:");
allContacts.forEach((contact, index) => {
console.log(`Contact ${index + 1}:`);
console.log(`Name: ${contact.getName()}`);
console.log(`Email: ${contact.getEmail()}`);
console.log(`Phone: ${contact.getPhone()}`);
});
In this code snippet, we create an AddressBook instance, add two contacts, and then retrieve and display all contacts.
Conclusion In this tutorial, we've built a basic Address Book Application in TypeScript. You can extend and enhance this application to include additional features like searching for contacts, editing contact information, and saving data to a database. This project serves as a foundation for understanding object-oriented design and TypeScript development.
Feel free to explore further and adapt this example for your own projects and applications. Happy coding!