root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 18 min

Typed functions and generics

โš‘ Report an issue with this lesson
function 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
typescript
Output

      
    

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