TypeScript Programming Example
Last Updated :
03 Mar, 2025
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
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
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
Web Development Technologies Web development refers to building, creating, and maintaining websites. It includes aspects such as web design, web publishing, web programming, and database management. It is the creation of an application that works over the internet, i.e., websites.To better understand the foundation of web devel
7 min read
CSS Tutorial CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and enhance website presentation. CSS is one of the three main components of a webpage, along with HTML and JavaScript.HTML adds Structure to a web page.JavaScript adds logic to it and CSS makes it visually appealing or
7 min read