Course contentsShow
← TypeScript
Lesson 531 of 1,79613. GenericsFree lesson

Type Parameters vs any

Comparing how generics preserve type information while any loses it, showing why generics are safer.

Type Parameters vs any

You'll learn why generics preserve type information while any throws it away, making your code safer.

The Problem with any

When you use any, TypeScript gives up. It stops tracking what type something actually is, and you lose all type safety:

function identity(value: any): any {
  return value;
}

const result = identity("hello");
// result is typed as `any` - TypeScript has no idea it's a string!
result.toUpperCase(); // No error, but no help either
result.nonExistentMethod(); // TypeScript allows this nonsense!

How Type Parameters Preserve Information

Generics act like a type variable that remembers what you passed in:

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

const result = identity("hello");
// result is typed as `string` - TypeScript knows exactly what it is!
result.toUpperCase(); // Works perfectly
result.nonExistentMethod(); // Error: Property doesn't exist!

The Key Difference

Think of any like a lockbox that destroys the label on whatever you put inside. You get something back, but you've forgotten what it was.

Type parameters are like a transparent container with a label that follows the value around. You can always see what's inside and TypeScript enforces correctness.

With any, this compiles but breaks at runtime:

const num: any = identity(42);
num.toUpperCase(); // Compiles, crashes at runtime

With generics, TypeScript catches the mistake:

const num = identity(42); // num is number
num.toUpperCase(); // Error: toUpperCase doesn't exist on number

Key Takeaway: Type parameters preserve type information through your functions, enabling type safety and autocomplete, while any erases all type knowledge and defeats the purpose of TypeScript.