<vetted />
TypeScript
Mid-Level
Question 4 of 8

How do you write reusable code in TypeScript that works with different types?

Quick Answer

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

Detailed Answer4 paragraphs

Generics in TypeScript are a way to create reusable components that work with a variety of types rather than a single one. They allow you to capture the type a user provides so that it can be used later, enabling type-safe code that doesn't sacrifice flexibility.

The most common use case is with functions. Instead of using 'any' (which loses type information), you can use a generic type parameter: function identity<T>(arg: T): T { return arg; }. When you call this function, TypeScript infers the type or you can explicitly specify it.

Generics are extensively used in: container types (Array<T>, Map<K, V>), utility types (Partial<T>, Pick<T, K>), async operations (Promise<T>), and React components (FC<Props>). They allow libraries to provide type-safe APIs without knowing the specific types users will provide.

You can constrain generics using extends: <T extends object> ensures T is an object type. You can use multiple type parameters (<T, K extends keyof T>) and provide default types (<T = string>). Understanding generics is essential for writing reusable TypeScript code and understanding library type definitions.

Key Takeaway

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

Ace your interview

Ready to Land Your Dream Job?

Join our network of elite AI-native engineers.