Typed functions and generics
โ Report an issue with this lessonfunction describe(course: Course): string {
return `${course.title} -- $${course.price}`;
}
function firstItem<T>(items: T[]): T | undefined {
return items[0];
}
firstItem<string>(["a", "b"]); // T inferred as string
Generics let a function stay type-safe while working across many types โ the same idea as generics in Java or C++, adapted to JavaScript's structural type system.
Try it yourself
Exercise: Write a generic firstItem<T> function that returns the first element of an array.
Expected output:
a
Run your code and get it working before marking this lesson complete.
// that was the last free lesson
9 more lessons โ including Capstone project: typed API client โ plus a certificate are waiting.
Unlock the full course โ $149.99