Welcome to The Coding College, your partner in coding excellence. At The Coding College, we believe that practice makes perfect, especially when mastering TypeScript. Below, you’ll find a collection of hands-on TypeScript exercises ranging from beginner to advanced levels, designed to help you sharpen your TypeScript skills.
Beginner-Level Exercises
1. Hello, TypeScript!
Objective: Write a simple TypeScript program that displays “Hello, TypeScript!” in the console.
Code Example:
function greet(): void {
console.log("Hello, TypeScript!");
}
greet();
Challenge: Modify the program to take a name as an argument and display “Hello, [Name]!”.
2. Type Annotations
Objective: Create a function that takes two numbers as arguments and returns their sum.
Code Example:
function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(addNumbers(5, 10)); // Output: 15
Challenge: Add type annotations for the function’s arguments and return value.
3. Arrays and Loops
Objective: Declare an array of numbers and calculate their sum using a loop.
Code Example:
const numbers: number[] = [1, 2, 3, 4, 5];
let sum = 0;
for (const num of numbers) {
sum += num;
}
console.log("Sum:", sum);
Challenge: Rewrite the program using the reduce
method.
Intermediate-Level Exercises
4. Using Interfaces
Objective: Create an interface for a Person
object with properties like name
, age
, and isStudent
. Write a function that prints a person’s details.
Code Example:
interface Person {
name: string;
age: number;
isStudent: boolean;
}
function printPerson(person: Person): void {
console.log(`Name: ${person.name}, Age: ${person.age}, Is Student: ${person.isStudent}`);
}
const john: Person = { name: "John", age: 25, isStudent: true };
printPerson(john);
Challenge: Add a method introduce
to the Person
interface that prints “Hi, I’m [Name].”
5. Tuples and Enums
Objective: Create a tuple to store a user’s ID and name. Use an enum to define user roles (e.g., Admin, User).
Code Example:
enum Role {
Admin,
User,
Guest
}
const user: [number, string, Role] = [1, "Alice", Role.Admin];
console.log(`ID: ${user[0]}, Name: ${user[1]}, Role: ${Role[user[2]]}`);
Challenge: Add a function that returns a user’s role as a string.
6. Type Aliases and Union Types
Objective: Create a type alias for a string
or number
. Write a function that takes this type and logs its type.
Code Example:
type StringOrNumber = string | number;
function logType(value: StringOrNumber): void {
console.log(typeof value);
}
logType("Hello"); // Output: string
logType(123); // Output: number
Challenge: Modify the function to handle only strings or numbers with specific logic for each.
Advanced-Level Exercises
7. Generics
Objective: Write a generic function that reverses an array of any type.
Code Example:
function reverseArray<T>(arr: T[]): T[] {
return arr.reverse();
}
console.log(reverseArray([1, 2, 3])); // Output: [3, 2, 1]
console.log(reverseArray(["a", "b", "c"])); // Output: ["c", "b", "a"]
Challenge: Modify the function to work with readonly arrays.
8. Classes and Inheritance
Objective: Create a Shape
class with a method to calculate area. Extend it to create Rectangle
and Circle
classes.
Code Example:
class Shape {
getArea(): number {
return 0;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
getArea(): number {
return this.width * this.height;
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
}
const rect = new Rectangle(10, 5);
const circle = new Circle(7);
console.log("Rectangle Area:", rect.getArea());
console.log("Circle Area:", circle.getArea());
Challenge: Add a method to calculate the perimeter for each shape.
9. Utility Types
Objective: Create a Partial
type for an object and a Readonly
type for another.
Code Example:
interface User {
id: number;
name: string;
age: number;
}
const updateUser: Partial<User> = { age: 30 };
const readonlyUser: Readonly<User> = { id: 1, name: "Alice", age: 25 };
// readonlyUser.age = 26; // Error: Cannot assign to 'age' because it is a read-only property.
Challenge: Use Pick
to select specific properties from the User
interface.
How to Approach These Exercises
- Start Simple: Begin with beginner-level exercises to build confidence.
- Incrementally Advance: Gradually move to intermediate and advanced exercises.
- Experiment: Modify the examples to test different scenarios.
- Practice Daily: Consistent practice will help solidify your knowledge.
Conclusion
TypeScript exercises are a great way to enhance your understanding of the language while building practical skills. From basic syntax to advanced concepts like generics and utility types, these exercises cater to learners of all levels.