Command Palette

Search for a command to run...

Hectal
Phase 12: The Compiler and tsconfig
TypeScript · Exercise 3 of 6 PreviousNext
Intermediate

Reading by Index Safely

noUncheckedIndexedAccess is on, so items[items.length - 1] has the type number | undefined: the list might be empty. lastOf promises a number, so the checker rejects it.

Make lastOf return the last item, or 0 when the list is empty, without using ! or as. The console must print 3 and 0.

What Check tests

  1. Your code has no type errors
  2. The console prints 3 and 0
  3. lastOf("abc") is rejected by TypeScript
  4. No ! and no as assertion

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.