Explain how generics work in typescript
- User
Explain how generics work in typescript
Assistant
Generics in TypeScript
Generics in TypeScript allow you to create reusable functions, classes, and interfaces that can work with multiple types, rather than a single one. This feature helps to ensure type safety while providing flexibility and reusability.
Why Generics?
Without generics, you might be tempted to use the
anytype to create reusable functions or classes. However, usinganycan lead to type errors and make your code less maintainable.typescriptfunction identity(arg: any): any { return arg; } const result = identity('hello'); // result is of type anyIn the example above, the
identityfunction takes an argument of typeanyand returns a value of typeany. However, when we call the function with a string argument, the return type is stillany, which means we've lost type information.Basic Generics
To fix this issue, we can use generics to create a reusable function that preserves type information.
typescriptfunction identity<T>(arg: T): T { return arg; } const result = identity('hello'); // result is of type string const result2 = identity(123); // result2 is of type numberIn this example, we've added a type parameter
Tto theidentityfunction. TheTtype parameter is a placeholder for the actual type that will be used when the function is called. When we call the function with a string argument, theTtype parameter is replaced with thestringtype, and when we call it with a number argument,Tis replaced with thenumbertype.Generic Types
We can also use generics with types, such as interfaces and classes.
typescriptinterface Container<T> { value: T; } const stringContainer: Container<string> = { value: 'hello' }; const numberContainer: Container<number> = { value: 123 };In this example, we've defined an interface
Container<T>that has a property of type . We can then create objects that conform to this interface, specifying the actual type for .