-
Book Overview & Buying
-
Table Of Contents
Full-Stack Web Development with TypeScript 5
By :
Generics in TypeScript are a tool for creating reusable components that can work with multiple types rather than a single one. This allows for better component abstraction while maintaining type safety as well. It also helps to write more flexible code that can adapt to different types. Let’s start with a basic example given here:
function printValue<T>(value: T): void {
console.log(value);
}
printValue<number>(123);
printValue<string>("Hello"); <T> is a generic type parameter that allows this function to accept any type of value. When you call printValue<number>(123) and printValue<string>("Hello"), TypeScript treats T as number and string, respectively. This demonstrates how generics provide flexibility without losing the benefits of type checking.
We also can improve InMemoryChatResource, which we defined before. It works fine now, but what if we also need an in-memory implementation...