WeCodeAcademy

Generics

A generic is a type placeholder, written <T>, so one function works for many types while keeping them safe.

Exampletypescript
Open in editor »

T is filled in from how you call the function. The type of the result follows the type of the input.

Exampletypescript
Open in editor »
Quick check

What is `T` in `function first<T>(items: T[])`?

Your turn: write the code

Write a generic last<T>(items: T[]): T | undefined that returns the last item. Print last([1, 2, 3]) and last(["a", "b"]).

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.