Generic Outside Class

This lesson shows how to use generic outside the concept of classes.

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.

Press + to interact
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 can ...