Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

TypeScript Practical Examples

Strengthen your TypeScript programming skills with practical examples. Learn to solve problems using functions, strings, arrays, objects, interfaces, and real-world business logic.

Learning objective: Practise writing reusable functions, transforming data, working with typed objects, filtering records, and solving common programming problems.

1. Why Practise TypeScript Examples?

Practical coding helps you understand how TypeScript concepts work together. Instead of learning only individual syntax rules, you solve problems using variables, functions, types, arrays, objects, and conditions.

🧠
Understand

Identify the problem and required result.

💻
Write Code

Use TypeScript types and programming logic.

✅
Test Result

Check the output with different inputs.

2. Example: Addition of Two Numbers

Create a function that accepts two numbers and returns their sum. This example demonstrates parameter types and return types.

function addNumbers(
    a: number,
    b: number
): number {
    return a + b;
}

const result = addNumbers(20, 30);

console.log("Sum: " + result);

Expected Output

Sum: 50

Explanation

  • a: number and b: number define number parameters.
  • The return type : number specifies the expected result type.
  • The function can be reused with different numbers.

3. Example: Check Even or Odd

Use the remainder operator % to determine whether a number is divisible by two.

function checkEvenOdd(number: number): string {
    if (number % 2 === 0) {
        return "Even";
    }

    return "Odd";
}

console.log(checkEvenOdd(10));
console.log(checkEvenOdd(7));
console.log(checkEvenOdd(0));

Expected Output

Even
Odd
Even
Concept: If the remainder after division by two is zero, the number is even.

4. Example: Reverse a String

A string can be converted into an array of characters, reversed, and joined back into a string.

function reverseString(text: string): string {
    return text.split("").reverse().join("");
}

console.log(reverseString("TypeScript"));
console.log(reverseString("CIIT"));

Expected Output

tpircSepyT
TIIC

Methods Used

split("")

Converts the string into an array of UTF-16 code-unit substrings.

reverse()

Reverses the array in place.

join("")

Combines array elements into a string.

Note: This simple method works for common English text. Complex Unicode characters, such as some emoji and combined characters, may need a more advanced grapheme-aware approach.

5. Example: Find the Largest Number in an Array

Use a loop to compare the elements and find the largest value. This example also demonstrates how to handle an empty array.

function findLargest(numbers: number[]): number | undefined {
    if (numbers.length === 0) {
        return undefined;
    }

    let largest = numbers[0];

    for (const number of numbers) {
        if (number > largest) {
            largest = number;
        }
    }

    return largest;
}

console.log(findLargest([12, 45, 23, 67, 34]));
console.log(findLargest([-8, -3, -15]));

Expected Output

67
-3
Why number | undefined? An empty array has no largest element. The return type communicates that the function may return a number or undefined.

6. Example: Calculate Array Sum and Average

Calculate the total and average of an array of marks using the reduce() method.

function calculateTotal(marks: number[]): number {
    return marks.reduce(
        (total, mark) => total + mark,
        0
    );
}

function calculateAverage(marks: number[]): number | undefined {
    if (marks.length === 0) {
        return undefined;
    }

    return calculateTotal(marks) / marks.length;
}

const marks = [80, 75, 90, 85];

console.log("Total: " + calculateTotal(marks));
console.log("Average: " + calculateAverage(marks));

Expected Output

Total: 330
Average: 82.5

An empty array would produce undefined for the average, because no average can be calculated without values.

7. Example: Filter Passed Students

Use filter() to return only the students whose marks meet the passing requirement.

interface StudentResult {
    name: string;
    marks: number;
}

const students: StudentResult[] = [
    { name: "Rahul", marks: 85 },
    { name: "Priya", marks: 35 },
    { name: "Amit", marks: 72 },
    { name: "Sneha", marks: 28 }
];

const passedStudents = students.filter(
    student => student.marks >= 40
);

passedStudents.forEach(student => {
    console.log(student.name + ": " + student.marks);
});

Expected Output

Rahul: 85
Amit: 72
Concept: The interface defines the structure of each student result. The filter() method creates an array containing only records that satisfy the condition.

8. Example: Search for a Student

Use find() to search for the first matching object in an array.

interface Student {
    id: number;
    name: string;
    course: string;
}

const studentList: Student[] = [
    { id: 101, name: "Rahul", course: "TypeScript" },
    { id: 102, name: "Priya", course: "Java" },
    { id: 103, name: "Amit", course: ".NET" }
];

function findStudent(id: number): Student | undefined {
    return studentList.find(student => student.id === id);
}

const result = findStudent(102);

if (result) {
    console.log("Name: " + result.name);
    console.log("Course: " + result.course);
} else {
    console.log("Student not found");
}

Expected Output

Name: Priya
Course: Java

The return type Student | undefined indicates that a matching record might not exist.

9. Example: Sort Products by Price

Use sort() with a comparison function to sort numeric values stored in an array of objects.

interface Product {
    name: string;
    price: number;
}

const products: Product[] = [
    { name: "Keyboard", price: 1200 },
    { name: "Mouse", price: 500 },
    { name: "Monitor", price: 8000 }
];

const sortedProducts = [...products].sort(
    (a, b) => a.price - b.price
);

sortedProducts.forEach(product => {
    console.log(product.name + ": Rs. " + product.price);
});

Expected Output

Mouse: Rs. 500
Keyboard: Rs. 1200
Monitor: Rs. 8000
Why use [...products]? It creates a shallow copy before sorting, preserving the original array's order.

10. Example: Remove Duplicate Numbers

Use a Set to keep only unique values from an array.

function removeDuplicates(numbers: number[]): number[] {
    return [...new Set(numbers)];
}

const values = [10, 20, 10, 30, 20, 40];

console.log(removeDuplicates(values));

Expected Output

[10, 20, 30, 40]

A Set stores unique values and preserves their insertion order.

11. Example: Count Vowels in a String

Convert the string to lowercase and count occurrences of the vowels a, e, i, o, and u.

function countVowels(text: string): number {
    const normalizedText = text.toLowerCase();
    let count = 0;

    for (const character of normalizedText) {
        if ("aeiou".includes(character)) {
            count++;
        }
    }

    return count;
}

console.log(countVowels("TypeScript"));
console.log(countVowels("Education"));

Expected Output

2
5

This example counts the five standard English vowels, not every possible vowel sound or accented character.

12. Example: Create a Grade Calculator

Use conditional statements to convert marks into a grade. The grade boundaries below are illustrative rules for this example.

function calculateGrade(marks: number): string {
    if (marks < 0 || marks > 100) {
        return "Invalid Marks";
    }

    if (marks >= 90) {
        return "A";
    }

    if (marks >= 75) {
        return "B";
    }

    if (marks >= 60) {
        return "C";
    }

    if (marks >= 40) {
        return "D";
    }

    return "Fail";
}

console.log(calculateGrade(95));
console.log(calculateGrade(78));
console.log(calculateGrade(52));
console.log(calculateGrade(30));

Expected Output

A
B
D
Fail
Note: The grade boundaries are example values. Use the actual grading scheme required by your institute or application.

13. Example: Calculate a Shopping Cart Total

This example shows a common business requirement: calculate a customer's total order value from multiple products and quantities.

interface CartItem {
    productName: string;
    price: number;
    quantity: number;
}

const cart: CartItem[] = [
    { productName: "Keyboard", price: 1200, quantity: 1 },
    { productName: "Mouse", price: 500, quantity: 2 },
    { productName: "USB Cable", price: 200, quantity: 3 }
];

function calculateCartTotal(items: CartItem[]): number {
    return items.reduce(
        (total, item) => total + item.price * item.quantity,
        0
    );
}

console.log("Cart Total: Rs. " + calculateCartTotal(cart));

Expected Output

Cart Total: Rs. 2800

Calculation

Product Price Quantity Subtotal
Keyboard ₹1,200 1 ₹1,200
Mouse ₹500 2 ₹1,000
USB Cable ₹200 3 ₹600
Total ₹2,800
Real-world connection: This pattern can be used in shopping carts, billing software, and order summaries. Real payment systems also need server-side validation and careful money handling.

14. TypeScript Concepts Used in These Examples

Concept Used For
Function Parameters Passing values to reusable functions.
Return Types Declaring the kind of value a function returns.
Interfaces Defining the expected structure of an object.
Arrays Storing and processing collections of values.
map(), filter(), reduce() Transforming, selecting, and aggregating data.
Conditional Statements Making decisions based on data and business rules.
Union Types Representing more than one possible result type.
Set Removing duplicate primitive values.

15. Practice Tasks for Students

Try solving these tasks independently before checking the solutions.

Task 1: Factorial

Write a function that calculates the factorial of a non-negative integer.

Task 2: Palindrome

Check whether a word reads the same forward and backward.

Task 3: Second Largest

Find the second-largest distinct number in an array.

Task 4: Employee Payroll

Define an Employee interface and calculate a sample salary total.

Task 5: Product Search

Search for a product by ID and handle missing products.

Task 6: Array Statistics

Calculate the minimum, maximum, total, and average of an array.

16. Best Practices

  • Give variables, functions, and interfaces meaningful names.
  • Define appropriate parameter and return types.
  • Handle empty arrays and missing records explicitly.
  • Test valid, invalid, boundary, and unexpected inputs.
  • Use reusable functions instead of duplicating logic.
  • Remember that TypeScript types help during development but do not automatically validate external data at runtime.

Summary

  • Functions make programming logic reusable.
  • String methods help process textual data.
  • Arrays support searching, filtering, sorting, and aggregation.
  • Interfaces define the structure of application objects.
  • Union types represent multiple possible result types.
  • Business examples connect TypeScript syntax with practical application requirements.
  • Testing different inputs improves problem-solving and debugging skills.