Search⌘ K

Generic Outside Class

Explore how generics can be used in TypeScript functions beyond classes to improve type safety and versatility. Understand why generics outperform unknown types by handling type mismatches effectively, enabling more robust and reusable code.

Generic with function #

Generic is a concept that is not limited to classes. It can also be used directly on global functions or interfaces. You can have a function that takes generic parameters and also returns a generic type.

TypeScript 3.3.4
function countElementInArray<T>(elements: T[]): number {
return elements.length;
}
function returnFirstElementInArray<T>(elements: T[]): T | undefined {
if (elements.length > 0) {
return elements[0];
}
return undefined;
}
const arr = [1, 2, 3];
console.log(countElementInArray(arr));
console.log(returnFirstElementInArray(arr));

The two functions are examples of what ...