Open In App

TypeScript Programming Example

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

TypeScript is a popular superset of JavaScript that adds static typing and other features to improve the development experience. In this blog post, we’ll explore practical examples of TypeScript that demonstrate how it can be used to solve common development challenges.

TypeScript Programming Example
TypeScript Programming


Tip: Before, directly jumping into Typescript Programming we would recommend first strengthening your fundamentals with our typescript tutorial.

1. Data Types in TypeScript

TypeScript provides a rich set of data types that allow developers to define the kind of data a variable can hold.

JavaScript
// 1. Primitive Types
let age: number = 25;
let name: string = "Alice";
let isActive: boolean = true;
let emptyValue: null = null;
let unassignedValue: undefined = undefined;

// 2. Special Types
let dynamicValue: any = 10;
dynamicValue = "Hello";

let unknownValue: unknown = "Hello";

function logMessage(): void {
    console.log("This is a log message.");
}

function throwError(message: string): never {
    throw new Error(message);
}

// 3. Object Types
let user: { name: string; age: number } = { name: "Alice", age: 25 };

// 4. Array Types
let numbers: number[] = [1, 2, 3, 4];
let names: string[] = ["Alice", "Bob", "Charlie"];

// 5. Tuple Types
let person: [string, number] = ["Alice", 25];

// 6. Custom Types
type Point = { x: number; y: number };
let p1: Point = { x: 10, y: 20 };

interface User {
    name: string;
    age: number;
}
let user2: User = { name: "Bob", age: 30 };

// 7. Union and Intersection Types
let id: string | number = "123";
id = 456;

type Person = { name: string };
type Employee = { id: number };
let employee: Person & Employee = { name: "Alice", id: 123 };

// 8. Literal Types
let direction: "left" | "right" | "up" | "down" = "left";

// 9. Enum Types
enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE",
}
let color: Color = Color.Green;

// Output
console.log(age, name, isActive, emptyValue, unassignedValue);
console.log(dynamicValue);
console.log(unknownValue);
logMessage();
// throwError("Something went wrong!");
console.log(user);
console.log(numbers, names);
console.log(person);
console.log(p1);
console.log(user2);
console.log(id);
console.log(employee);
console.log(direction);
console.log(color);

In this Example:

  • Primitive Types: Basic data types like number, string, boolean.
  • Special Types: Any dynamic and unknown type-safe dynamic.
  • Custom Types: Uses type and interface to define object structures.

Output

25 Alice true null undefined
Hello
Hello
This is a log message.
{ name: 'Alice', age: 25 }
[1, 2, 3, 4] ['Alice', 'Bob', 'Charlie']
['Alice', 25]
{ x: 10, y: 20 }
{ name: 'Bob', age: 30 }
456
{ name: 'Alice', id: 123 }
left
GREEN

2. Function In Typescript

Functions in TypeScript are similar to JavaScript functions but with added features like type annotations for parameters and return values.

JavaScript
// 1. Basic Function
function add(a: number, b: number): number {
    return a + b;
}
console.log("Basic Function:", add(5, 10)); 

// 2. Optional Parameters
function greet(name: string, age?: number): string {
    if (age) {
        return `Hello, ${name}! You are ${age} years old.`;
    } else {
        return `Hello, ${name}!`;
    }
}
console.log("Optional Parameters:");
console.log(greet("Alice")); 
console.log(greet("Bob", 30)); 

// 3. Default Parameters
function greetDefault(name: string, age: number = 25): string {
    return `Hello, ${name}! You are ${age} years old.`;
}
console.log("Default Parameters:");
console.log(greetDefault("Alice")); 
console.log(greetDefault("Bob", 30)); 

// 4. Rest Parameters
function sum(...numbers: number[]): number {
    return numbers.reduce((total, num) => total + num, 0);
}
console.log("Rest Parameters:", sum(1, 2, 3, 4)); // Output: 10

// 5. Arrow Functions
const multiply = (a: number, b: number): number => a * b;
console.log("Arrow Function:", multiply(5, 3)); // Output: 15

// 6. Function Overloading
function combine(a: string, b: string): string;
function combine(a: number, b: number): number;
function combine(a: any, b: any): any {
    return a + b;
}
console.log("Function Overloading:");
console.log(combine("Hello, ", "World!")); // Output: Hello, World!
console.log(combine(5, 10)); // Output: 15

// 7. Void Functions
function logMessage(message: string): void {
    console.log("Void Function:", message);
}
logMessage("This is a log message."); 

// 8. Never Type
function throwError(message: string): never {
    throw new Error(message);
}
// console.log("Never Type:", throwError("Something went wrong!")); // Throws an error

In this Example:

  • Type Annotations: Shows how to define parameter and return types.
  • Optional/Default: Demonstrates ? and = for function parameters.
  • Overloading: Shows how to define multiple function signatures.

Output

Basic Function: 15
Optional Parameters:
Hello, Alice!
Hello, Bob! You are 30 years old.
Default Parameters:
Hello, Alice! You are 25 years old.
Hello, Bob! You are 30 years old.
Rest Parameters: 10
Arrow Function: 15
Function Overloading:
Hello, World!
15
Void Function: This is a log message.

3. Array In Typescript

In TypeScript, an array is an ordered collection of values, potentially of mixed types, accessed by zero-based indices. TypeScript encourages using homogeneous arrays (elements of the same type) for better type safety and readability.

JavaScript
// 1. Basic Array
let numbers: number[] = [1, 2, 3, 4, 5];
console.log("Basic Array:", numbers);

// 2. Array of Strings
let fruits: string[] = ["Apple", "Banana", "Orange"];
console.log("Array of Strings:", fruits); 

// 3. Mixed-Type Array
let mixedArray: (string | number)[] = ["Apple", 10, "Banana", 20];
console.log("Mixed-Type Array:", mixedArray); 

// 4. Array of Objects
interface Person {
    name: string;
    age: number;
}

let people: Person[] = [
    { name: "Geeks", age: 25 },
    { name: "ForGeeks", age: 30 },
];
console.log("Array of Objects:", people); 

// 5. Readonly Array
let readOnlyNumbers: readonly number[] = [1, 2, 3];
// readOnlyNumbers.push(4);
console.log("Readonly Array:", readOnlyNumbers); // Output: [1, 2, 3]

// 6. Tuple 
let person: [string, number] = ["Geeks", 25];
console.log("Tuple:", person); // Output: ['Alice', 25]

// 7. Array Methods
let numbersArray: number[] = [1, 2, 3, 4, 5];

// Map
let doubledNumbers = numbersArray.map((num) => num * 2);
console.log("Map:", doubledNumbers); // Output: [2, 4, 6, 8, 10]

// Filter
let evenNumbers = numbersArray.filter((num) => num % 2 === 0);
console.log("Filter:", evenNumbers); // Output: [2, 4]

// Reduce: Accumulate values into a single result
let sum = numbersArray.reduce((total, num) => total + num, 0);
console.log("Reduce:", sum); // Output: 15

// 8. Spread Operator
let newNumbers = [...numbersArray, 6, 7, 8];
console.log("Spread Operator:", newNumbers); 

// 9. Destructuring Arrays
let [first, second, ...rest] = numbersArray;
console.log("Destructuring:");
console.log("First:", first); // Output: 1
console.log("Second:", second); // Output: 2
console.log("Rest:", rest); // Output: [3, 4, 5]

In this Example:

  • Typed Arrays: Shows how to create arrays with specific element types.
  • Array Methods: Demonstrates map, filter, and reduce.
  • Spread/Destructuring: Shows array manipulation techniques.

Output

Basic Array: [1, 2, 3, 4, 5]
Array of Strings: ['Apple', 'Banana', 'Orange']
Mixed-Type Array: ['Apple', 10, 'Banana', 20]
Array of Objects: [{ name: 'Geeks', age: 25 }, { name: 'ForGeeks', age: 30 }]
Readonly Array: [1, 2, 3]
Tuple: ['Geeks', 25]
Map: [2, 4, 6, 8, 10]
Filter: [2, 4]
Reduce: 15
Spread Operator: [1, 2, 3, 4, 5, 6, 7, 8]
Destructuring:
First: 1
Second: 2
Rest: [3, 4, 5]

4. Enum In Typescript

In TypeScript, an enum (short for "enumeration") is a way to define a set of named constants. It provides a more readable and manageable way to work with a fixed set of values, compared to using plain numbers or strings.

JavaScript
enum Color {
  Red,
  Green,
  Blue,
}

let myColor: Color = Color.Green;
console.log(myColor); 
console.log(Color.Red); 
console.log(Color.Blue); 


In this Example:

  • Named Constants: Shows how to create enums with default numeric values.

Ouptut

  1
0
2

5. Alias & Literal Types In Typescript

Type aliases create new names for existing types, boosting readability and reusability without creating new types.Literal types represent specific, fixed values (strings, numbers, booleans, or template literals), restricting variables to those values.

JavaScript
// Alias: Create a custom type for reusability
type StringOrNumber = string | number;

// Literal Types: Restrict values to specific options
type Direction = "left" | "right" | "up" | "down";

// Using the Alias
let value: StringOrNumber;
value = "Hello"; 
value = 42;      
// value = true;

// Using the Literal Types
let move: Direction;
move = "left";   
move = "right";  

console.log(value); 
console.log(move);  

In this Example:

  • Type Aliases: Shows how to create custom type names.
  • Literal Types: Shows how to restrict values to specific strings.

Output

42
right

6. Type Assertion In Typescript

Type assertion in TypeScript allows you to override the compiler's type inference and explicitly tell it the type of a value. This is done using either angle bracket syntax (<type>value) or the as syntax (value as type).

JavaScript
let someValue: any = "Hello, TypeScript!";

// Type assertion using angle brackets
let strLength1: number = (<string>someValue).length;

// Type assertion using 'as' syntax
let strLength2: number = (someValue as string).length;

console.log(strLength1); 
console.log(strLength2); 

In this Example:

  • Type Overrides: Shows how to use as and <> to assert types.

Output

18
18

7. TS Classes in Typescript

TypeScript classes are blueprints for creating objects, defining their properties (data) and methods (behavior). Objects, also known as instances of a class, are created using the new keyword.

JavaScript
// Basic Class
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  makeSound() {
    console.log("Generic animal sound");
  }
}

// Subclass (Inheritance)
class Dog extends Animal {
  breed: string;
  constructor(name: string, breed: string) {
    super(name); // Calls the parent constructor
    this.breed = breed;
  }
  makeSound() { // Overrides the parent's makeSound
    console.log("Woof!");
  }

    // Getter
    get dogBreed(): string {
        return this.breed;
    }

    // Setter
    set dogBreed(neeed: string) {
        this.breed = newBreed;
    }
}

// Static Class Members
class MathUtils {
  static PI: number = 3.14159; 
  static add(a: number, b: number): number { 
    return a + b;
  }
}


let myDog = new Dog("Buddy", "Golden Retriever");
myDog.makeSound(); 
console.log(myDog.name);
console.log(myDog.breed); 

let myAnimal: Animal = new Animal("Some Animal"); 
myAnimal = myDog;
myAnimal.makeSound(); // Output: Woof!

// Using Getter and Setter
console.log(myDog.dogBreed);
myDog.dogBreed = "Labrador"; 
console.log(myDog.dogBreed); 


// Using Static Members
console.log(MathUtils.PI); 
let sum = MathUtils.add(5, 3);
console.log(sum); // Output: 8

In this Example:

  • Inheritance: Shows how to create subclasses.
  • Getters/Setters: Demonstrates property access control.
  • Static Members: Shows class-level properties and methods.

Output

Woof! 
Buddy
Golden Retriever
Woof! Golden
Retriever Labrador
3.14159
8

8. Object & Type & Interface

In TypeScript, objects are collections of key-value pairs, representing data with named properties. Types define the shape of data, specifying the kinds of values a variable or property can hold. Interfaces are a contract for the structure of objects, declaring required properties and their types, often used with classes to ensure they adhere to a specific form.

JavaScript
// Object (plain JavaScript object)
const myObject = {
  name: "Alice",
  age: 30,
};

// Type (defining the shape of an object)
type PersonType = {
  name: string;
  age: number;
};

// Interface (defining a contract for object structure)
interface PersonInterface {
  name: string;
  age: number;
}

let person1: PersonType = { name: "Bob", age: 25 }; 
let person2: PersonInterface = { name: "Charlie", age: 35 }; 
// Class implementing an interface
class Employee implements PersonInterface {
  name: string;
  age: number;
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

In this Example:

  • Object: Plain JavaScript object with key-value pairs.
  • Type/Interface: Define object structures with required properties.
  • Implementation: Shows how a class implements an interface.

Output

Alice 
Bob
Charlie
David
40

9. TS Generics In Typescript

Generics in TypeScript are a powerful feature that enables the creation of reusable components capable of working with a variety of types without sacrificing type safety. This is achieved through the use of type parameters, such as <T>, which act as placeholders for specific types that are determined only when the component is actually used.

JavaScript
// Basic Generic Usage
function identity<T>(arg: T): T {
  return arg;
}

let result1 = identity<string>("hello"); 
let result2 = identity(123);

console.log(result1); 
console.log(result2);

// Advanced Usage (with constraints)
interface Lengthy {
  length: number;
}

function logAndReturn<T extends Lengthy>(arg: T): T {
  console.log("Length:", arg.length);
  return arg;
}

let result3 = logAndReturn([1, 2, 3]); 

console.log(result3); 

// Generics in Classes
class Box<T> {
  private contents: T;

  constructor(contents: T) {
    this.contents = contents;
  }

  getContents(): T {
    return this.contents;
  }
}

let stringBox = new Box<string>("TypeScript");
let numberBox = new Box(42); 

console.log(stringBox.getContents()); 
console.log(numberBox.getContents()); 

In this Example:

  • Generic Function: Reusable function with type parameters.
  • Constraints: Limits generic types to those with specific properties.
  • Generic Class: Class with type parameters for flexible data handling.

Output

hello 
123
Length: 3
[1, 2, 3]
TypeScript
42

10. Utility in Typescript

TypeScript's utility types are a set of built-in types that provide convenient ways to perform common type transformations.

JavaScript
// Partial
interface Person {
  name: string;
  age: number;
}
type PartialPerson = Partial<Person>;
const p: PartialPerson = { name: "Alice" };

// Required & Readonly
type RequiredPerson = Required<PartialPerson>;
const rp: RequiredPerson = { name: "Eve", age: 28 };
type ReadonlyPerson = Readonly<Person>;
const rop: ReadonlyPerson = { name: "Mallory", age: 32 };

// Record
type Fruit = "apple" | "banana" | "orange";
type FruitPrices = Record<Fruit, number>;
const prices: FruitPrices = {
  apple: 1.00,
  banana: 0.50,
  orange: 0.75,
};

// Pick & Omit
type NameAndAge = Pick<Person, "name" | "age">;
const na: NameAndAge = { name: "Carol", age: 40 };
type PersonWithoutAge = Omit<Person, "age">;
const pwa: PersonWithoutAge = { name: "Dan" };

// Exclude & Extract
type FruitOrVegetable = "apple" | "banana" | "carrot" | "broccoli";
type FruitOnly = Exclude<FruitOrVegetable, "carrot" | "broccoli">;
type VegetableOnly = Extract<FruitOrVegetable, "carrot" | "broccoli">;

// NonNullable
type NullableString = string | null | undefined;
type NonNullableString = NonNullable<NullableString>;
const nnString: NonNullableString = "Hello";

// ReturnType
function greet(name: string): string {
  return "Hello, " + name;
}
type GreetingType = ReturnType<typeof greet>;

// Parameters
type GreetingParams = Parameters<typeof greet>;

console.log(p.name); 
console.log(rp.age);
console.log(prices.apple); 
console.log(na.name); 
console.log(pwa.name); 
console.log(nnString); 
console.log(typeof greet); 
console.log(typeof GreetingType);
console.log(typeof GreetingParams);

In this Example:

  • Type Transformations: Shows utility types like Partial, Readonly, Pick.
  • Type Operations: Demonstrates Exclude, Extract, NonNullable.
  • Function Types: Shows ReturnType and Parameters.

Output

Alice 
28
1
Carol
Dan
Hello
function
string
object

Next Article
Article Tags :

Similar Reads