Keypoints
- Show how to declare generic functions and classes in TypeScript.
- Provide examples of generic functions that work with different data types.
- Demonstrate the use of built-in generics like
Array<T>
andPromise<T>
.
Here’s the content for “Chapter 2: Basic Usage of Generics” in your TypeScript generics blog:
Basic Usage of Generics
Now that we have a solid understanding of what generics are and their historical context, it’s time to roll up our sleeves and dive into the practical world of TypeScript generics. In this chapter, we’ll explore the basics: declaring and using generic functions, demonstrating how they work with various data types, and leveraging built-in generics that TypeScript offers.
2.1 Declaring and Using Generic Functions
At the heart of TypeScript generics are generic functions. These functions provide a way to create code that can work with a variety of data types. Let’s start by understanding the fundamental steps of declaring and using generic functions.
To declare a generic function, you use the angle brackets (< >
) notation, often referred to as type parameters. Here’s a simple example:
function identity<T>(arg: T): T { return arg; }
In this example, T
is a type parameter. It serves as a placeholder for the actual data type that will be provided when the function is called. The type parameter T
allows us to keep the function flexible while ensuring type safety.
Now, let’s use the identity
function with different data types:
let value1 = identity<string>("Hello, TypeScript"); // Returns a string let value2 = identity<number>(42); // Returns a number
As you can see, we call the identity
function by specifying the type parameter within angle brackets. TypeScript infers the data type of the return value based on the type parameter we provide.
2.2 Generic Functions with Different Data Types
Generic functions truly shine when you need to work with various data types in a type-safe manner. Let’s explore how we can use generic functions with different data types:
function getLength<T>(input: T[]): number { return input.length; } const numbers = [1, 2, 3, 4, 5]; const fruits = ["apple", "banana", "cherry"]; const numCount = getLength(numbers); // Returns 5 const fruitCount = getLength(fruits); // Returns 3
In this example, the getLength
function takes an array of any data type and returns the length of the array. We don’t need to specify the data type explicitly when calling the function; TypeScript infers it based on the type of the argument.
2.3 Utility of Built-In Generics: Array<T> and Promise<T>
TypeScript offers a set of built-in generics that simplify common tasks. Two notable examples are Array<T>
and Promise<T>
.
- Array<T>: The
Array<T>
type allows you to create arrays that contain elements of a specific data type. This ensures that the array only contains elements of that type. For instance:
const numbers: Array<number> = [1, 2, 3, 4, 5]; const names: Array<string> = ["Alice", "Bob", "Charlie"];
- Promise<T>: Promises represent asynchronous operations that will eventually produce a result or an error. By using
Promise<T>
, you can specify the expected data type of the resolved value. For example:
function fetchUserData(): Promise<User> { // Fetch user data asynchronously and return a User object }
These built-in generics enhance code readability and provide type safety, reducing the likelihood of runtime errors.
With a solid grasp of declaring and using generic functions, as well as understanding the utility of built-in generics like Array<T>
and Promise<T>
, you’ve taken a significant step toward mastering TypeScript generics. In the next chapter, we’ll explore type constraints and extending generics, allowing us to fine-tune our generic code for even more specific use cases.