What are Generics?
Generics allow you to create reusable components that work with a variety of types rather than a single one.
Basic Syntax
You can define a generic function using angle brackets.
typescript
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
Constraints
Sometimes you want to limit the types that can be passed to a generic.
"Generics provide a way to make components work with any data type and not restrict to one data type."
Using extends keyof
typescript
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
