typescript
/

TypeScript Generics

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Generics

What are Generics?

Generics allow you to create reusable components that work with multiple data types while maintaining type safety.

Basic Generic Function

TypeScriptRead-only
1
function identity<T>(value: T): T {
  return value;
}

Using Generics

TypeScriptRead-only
1
identity<string>('Hello');
identity<number>(10);

Generic Interface

TypeScriptRead-only
1
interface Box<T> {
  value: T;
}

Generic Class

TypeScriptRead-only
1
class DataStore<T> {
  data: T[] = [];

  add(item: T) {
    this.data.push(item);
  }
}

Generic Constraints

TypeScriptRead-only
1
function printLength<T extends { length: number }>(item: T) {
  console.log(item.length);
}

Multiple Generics

TypeScriptRead-only
1
function pair<K, V>(key: K, value: V) {
  return { key, value };
}

Best Practices

  • Use generics for reusable logic
  • Keep generic names meaningful (T, K, V)
  • Use constraints when needed
  • Avoid overusing generics

Common Mistakes

  • Using generics unnecessarily
  • Not defining constraints
  • Complex generic definitions
  • Ignoring type safety benefits

Conclusion

Generics make TypeScript code more reusable, flexible, and type-safe, especially in large applications.

Try it yourself

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

Test Your Knowledge

Q1
of 3

Generic symbol?

A
<>
B
{}
C
[]
D
()
Q2
of 3

Generic used for?

A
Styling
B
Reuse
C
Routing
D
API
Q3
of 3

Constraint keyword?

A
extends
B
implements
C
type
D
class

Frequently Asked Questions

What is generic?

Reusable type with flexibility.

Why use generics?

To write reusable and type-safe code.

What is constraint?

Limiting generic types.

Previous

ts interfaces vs types

Next

ts utility types

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.