BudiBadu Logo
Samplebadu

TypeScript by Example: Generics

5.x

Master TypeScript generics to write reusable, type-safe code with this comprehensive code example. Shows generic functions, interfaces, explicit type arguments, and constraint syntax to create flexible components that work across multiple types while preserving type information.

Code

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

let output1 = identity<string>("myString");
let output2 = identity<number>(100);

// Generic Interface
interface Box<T> {
    contents: T;
}

let stringBox: Box<string> = { contents: "hello" };
let numberBox: Box<number> = { contents: 42 };

// Generic Constraints
interface Lengthwise {
    length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
    console.log(arg.length); // Now we know it has a .length property
    return arg;
}

Explanation

Generics allow you to write reusable code that works with multiple types while maintaining type safety. Instead of writing separate functions for strings, numbers, and other types, you can write one generic function using type variables like T. When you call a generic function, TypeScript infers the type from your arguments or you can specify it explicitly using angle brackets. This preserves type information throughout your code, unlike any which discards all type checking.

Generic constraints using extends let you restrict which types can be used with your generic code. In the example, T extends Lengthwise ensures that the type parameter has a length property. This gives you the flexibility of generics while still enforcing that certain properties or methods exist.

Advanced generic patterns include:

  • Multiple type parameters for functions operating on several types simultaneously
  • Default type parameters providing fallback types when none are specified
  • Generic constraints using extends to limit acceptable types
  • Type inference that automatically determines type arguments from function calls

Code Breakdown

2
<T> declares a generic type parameter.
6
identity<string> explicitly passes the type argument.
14
Box<T> creates a generic interface for any content type.
26
T extends Lengthwise constrains T to have a length property.