Command Palette

Search for a command to run...

Hectal
Phase 11: Modules and Declaration Files
TypeScript · Exercise 3 of 5 PreviousNext
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

  1. Your code has no type errors
  2. The program prints 3 and then undefined
  3. last() may return undefined, so using it as a number is rejected
  4. 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.

Console

Nothing printed yet.