JavaScript Development Space

How to Understand TypeScript Generics

TypeScript generics allow developers to create reusable components, making your code more flexible and maintainable. By using generics, you can create functions, classes, or interfaces that work with a variety of data types, instead of being limited to a single one.

1. What Are Generics?

Generics are essentially placeholders for types that are provided when you call a function, create an object, or define a class. Instead of hardcoding a specific type, generics let you define functions that work with any data type.

Example:

js
1 function identity<T>(arg: T): T {
2 return arg;
3 }

Here, T is the generic type that can be replaced with any type when calling the function. You could use this function with a number, string, or other types.

2. Why Use Generics?

Generics improve code reusability and maintain type safety. Instead of duplicating code for different types, you can define it once and ensure type checks happen automatically.

Benefits of Using Generics

Generics allow you to:

  • Write reusable code that can handle multiple data types.
  • Maintain type safety, ensuring that your types are consistent.
  • Avoid code duplication by eliminating the need for separate implementations for each type.

3. Generic Functions

You can define a generic function by adding the type parameter within angle brackets (<>) after the function name. This makes the function work with various types dynamically.

js
1 function getArray<T>(items: T[]): T[] {
2 return new Array().concat(items);
3 }
4
5 let numArray = getArray < number > [1, 2, 3];
6 let strArray = getArray < string > ['A', 'B', 'C'];

4. Generic Classes

Generics can also be applied to classes, allowing you to create structures that can work with different types.

js
1 class Box<T> {
2 contents: T;
3 constructor(value: T) {
4 this.contents = value;
5 }
6 }
7
8 let numberBox = new Box() < number > 10;
9 let stringBox = new Box() < string > 'hello';

5. Generic Constraints

Sometimes you might want to limit the types that can be used with generics. You can do this using constraints.

js
1 function loggingIdentity<T extends { length: number }>(arg: T): T {
2 console.log(arg.length);
3 return arg;
4 }

Here, the generic type T is constrained to types that have a length property, like arrays or strings.

6. Generic Interfaces

Interfaces can use generics to create flexible structures for different data types.

js
1 interface Pair<T, U> {
2 first: T;
3 second: U;
4 }
5
6 let pair: Pair<number, string> = { first: 1, second: 'one' };

Conclusion

Generics are a powerful feature in TypeScript that provide flexibility and reusability, while still maintaining type safety. By using generics effectively, you can write cleaner and more maintainable code.

JavaScript Development Space

© 2024 JavaScript Development Blog. All rights reserved.