Functions, Interfaces, and Constraints - Textnotes

Functions, Interfaces, and Constraints


Learn how to use generics in TypeScript to write reusable and type-safe code. This module explains generic functions, generic interfaces, and generic constraints with practical examples.

1. Generic Functions

Generics allow functions to work with multiple types while preserving type safety.

Basic Generic Function Example


function identity<T>(value: T): T {
return value;
}

let num = identity<number>(10); // num is number
let str = identity<string>("Muni"); // str is string

Generics make functions reusable without losing type information.

Generic Function with Arrays


function getFirstElement<T>(arr: T[]): T {
return arr[0];
}

let numbers = getFirstElement([1, 2, 3]); // number
let names = getFirstElement(["Muni", "Ravi"]); // string

2. Generic Interfaces

Generics can also be applied to interfaces to define reusable structures.

Basic Generic Interface Example


interface KeyValuePair<K, V> {
key: K;
value: V;
}

let pair: KeyValuePair<number, string> = { key: 1, value: "Muni" };

Generic interfaces are commonly used for collections, API responses, and reusable data structures.

Generic Interface with Functions


interface Repository<T> {
getById(id: number): T;
getAll(): T[];
}

This allows creating repositories for different entities without duplicating code.

3. Generic Constraints

Generic constraints restrict the types that can be used with generics, ensuring certain properties or methods exist.

Basic Constraint Example


interface Lengthwise {
length: number;
}

function logLength<T extends Lengthwise>(item: T): void {
console.log(item.length);
}

logLength("Hello"); // Works
logLength([1, 2, 3]); // Works
// logLength(10); // Error: number has no 'length' property

Constraints improve safety when working with unknown generic types.

Multiple Constraints Example


interface Nameable {
name: string;
}

function greet<T extends Nameable>(obj: T) {
console.log(`Hello, ${obj.name}`);
}

greet({ name: "Muni", age: 35 }); // Works

Conclusion

Generics in TypeScript enable reusable and type-safe code for functions, interfaces, and data structures. Using generic constraints further enhances safety while maintaining flexibility, making them essential for scalable real-world applications.