Bugs

TypeScript Generics: Common Mistakes and Fixes

Generics make TypeScript functions reusable while maintaining type safety. Incorrectly constrained generics either lose type information or restrict usage unnecessarily.


❌ Function That Loses Type

function first(arr: any[]): any {  // Input type is lost!
  return arr[0];
}

const name = first(['Alice', 'Bob']);  // name is 'any'
name.toUpperCase();  // No type safety!

✅ Type-Safe Generic Function

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const name = first(['Alice', 'Bob']);
// name is string | undefined
name?.toUpperCase();  // TypeScript knows it's a string method
💡

Pro tip: Use extends to constrain generics when the function needs specific properties: function getLength<T extends { length: number }> (obj: T): number

Paste this code into LearnCodeGuide

Detect TypeScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze TypeScript Code →

Related Guides

Typescript Type ErrorsTypescript Any Type AbuseTypescript Interface Vs Type