Typescript note - Generics

🤸‍♀️ Make Type generic with Generic

Created a function which reaturns the last number from the array.

1
2
3
4
5
6
const getLast = (arr: number[]) => {
return arr[arr.length - 1];
};

const lastNumber = getLast([1, 2, 3]);
console.log(lastNumber); // 3

It is happy 😊 But now, I need to get the last value from the array of string.
So,

1
2
3
4
5
6
7
8
9
const getLast = (arr: number[]) => {
return arr[arr.length - 1];
};

const lastNumber = getLast([1, 2, 3]);
console.log(lastNumber); // 3

const lastString= getLast(['a','b','c']); // ⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️
console.log(lastString);

😵😵😵 Then got errors…

error

🤔🤔🤔
.
.
.

💪 Generics solves the problem!!! 💪

1
2
3
const getLast = <T>(arr: T[]) => { // ⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️⬅️
return arr[arr.length - 1];
};

Now, the function accept any type 🙌🙌🙌