TypeScript Generics: Flexible and Type-Safe Code
In the previous articles, we explored TypeScript types, interfaces, and classes. In this article, we will dive into TypeScript generics, a powerful feature that allows you to create reusable components with flexible types while maintaining type safety. We will discuss how to create and use generic functions, classes, and interfaces.
Generic Functions
In TypeScript, you can create generic functions using type variables enclosed in angle brackets (<>
). Generic functions allow you to write a single function that can work with multiple types, while still maintaining type safety.
Here's an example of a generic function:
function identity(arg: T): T {
return arg;
}
const result1: string = identity("hello");
const result2: number = identity(42);
In the example above, the identity
function takes a single argument of type T
and returns a value of the same type. When calling the function, TypeScript infers the type of T
based on the argument passed.
Generic Classes
Just like functions, you can also create generic classes in TypeScript. A generic class is a class that takes one or more type variables. This allows you to create reusable, type-safe classes for a variety of data types.
Here's an example of a generic class:
class GenericArray {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
getItem(index: number): T {
return this.items[index];
}
}
const stringArray = new GenericArray();
stringArray.add("hello");
console.log(stringArray.getItem(0)); // Output: 'hello'
const numberArray = new GenericArray();
numberArray.add(42);
console.log(numberArray.getItem(0)); // Output: 42
Generic Interfaces
TypeScript also supports generic interfaces, allowing you to create flexible and type-safe interfaces for a variety of use cases. A generic interface is an interface that takes one or more type variables.
Here's an example of a generic interface:
interface KeyValuePair {
key: K;
value: V;
}
const pair1: KeyValuePair = {
key: "age",
value: 30
};
const pair2: KeyValuePair = {
key: 1,
value: ["apple", "banana", "orange"]
};
Conclusion
In this article, we covered TypeScript generics, including generic functions, classes, and interfaces. With generics, you can create flexible and type-safe components that can be reused with different data types. In the next article, we will explore organizing code with TypeScript modules.
Table of Contents: Typescript for Beginners
- An Introduction to TypeScript: JavaScript's Powerful Superset
- Understanding TypeScript Types
- Working with TypeScript Interfaces
- Mastering TypeScript Classes and Inheritance
- TypeScript Generics: Flexible and Type-Safe Code
- Organizing Code with TypeScript Modules
- Advanced TypeScript Types and Techniques
- Using TypeScript Decorators to Enhance Your Code
- Configuring the TypeScript Compiler for Your Project
- TypeScript Best Practices for Cleaner and More Maintainable Code