← TypeScript Foundations
15 / 25
Lesson 15 — Generic functions
Generic helpers for arrays
When a function takes an array, T[] means "an array of some type T", and returning T means "one item of that same type". If the array may be empty, be honest and return T | undefined — TypeScript will then remind callers to handle the missing case.
function last<T>(items: T[]): T | undefined {
return items[items.length - 1];
}
last([1, 2, 3]); // number | undefined
Why it matters: small generic helpers like this get reused all over a codebase with full type safety.
Want it another way?
Task
Make first return the first element of any array (undefined for an empty one). Expect 10, a, undefined.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.