Intermediate
Add last() to every array
Make [1, 2, 3].last() work and type-check. Add the type with declare global and interface Array<T>: last() returns the last item, or undefined for an empty array (T | undefined).
Then add the real method on Array.prototype, because a type alone creates no code. The program prints 3 and then undefined.
(Changing built-in prototypes is risky in real projects; this exercise is about how augmentation works.)
What Check tests
- Your code has no type errors
- The program prints 3 and then undefined
- last() may return undefined, so using it as a number is rejected
- last() on strings is accepted
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
Runs in your browser. Your code is saved here.
Press Run to see the page.
Console
Nothing printed yet.