Generics are a powerful feature in TypeScript that enable you to create reusable components. They allow you to write flexible, type-safe code that can work with multiple data types.
Generics provide a way to make components work with any data type and not restrict to one data type. They help you create a component that can work over a variety of types rather than a single one.
To define a generic function or class, use angle brackets <T>
where T is a type parameter:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
console.log(output); // Output: myString
You can restrict the types that a generic type parameter can accept using the extends
keyword:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know it has a .length property
return arg;
}
For more advanced usage of generics with constraints, check out the Generic Constraints guide.
Generics can also be used with classes:
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
T
is common, descriptive names like TEntity
or TKey
can improve readability.To deepen your understanding of TypeScript and how it relates to generics, explore these related topics:
Generics are a fundamental concept in TypeScript that enable you to write more flexible and reusable code. By mastering generics, you'll be able to create robust, type-safe components that can work with a variety of data types.