JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
Next
typescript
mid
generics

What are generics in TypeScript and how do you use them?

generics
type-parameters
constraints
inference
reusability
Quick Answer

Generics allow creating reusable components that work with multiple types while maintaining type safety. They use type parameters (like <T>) that are specified when the component is used, enabling type inference and constraints.

Detailed Explanation

What Generics Do:

  • Create reusable, type-safe components
  • Work with any type while preserving type information
  • Avoid using any and losing type safety
  • Enable type inference at call sites

Generic Syntax:

  • Type parameter: <T> (can be any name)
  • Multiple parameters: <T, U, K>
  • Constraints: <T extends SomeType>
  • Defaults: <T = DefaultType>

Where to Use:

  • Functions that work with various types
  • Classes/interfaces for containers
  • Utility types and type transformations

Code Examples

Generic functions
// Without generics - lose type information
function firstAny(arr: any[]): any {
  return arr[0];
}
const result = firstAny([1, 2, 3]); // type: any

// With generics - preserve type
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const num = first([1, 2, 3]);        // type: number
const str = first(['a', 'b']);       // type: string
const user = first([{ name: 'Alice' }]); // type: { name: string }

// Multiple type parameters
function pair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

const p = pair('hello', 42); // type: [string, number]

// Generic with inference
function map<T, U>(arr: T[], fn: (item: T) => U): U[] {
  return arr.map(fn);
}

const lengths = map(['hello', 'world'], s => s.length);
// lengths: number[] (inferred!)

Resources

TypeScript - Generics

docs

Related Questions

What are TypeScript's built-in utility types and when do you use them?

mid
utility-types

How do conditional types work in TypeScript?

senior
conditional-types
Next
What are type guards in TypeScript and how do you create custom ones?