Command Palette

Search for a command to run...

Hectal
Phase 16: Advanced TypeScript
TypeScript · Exercise 4 of 6 PreviousNext
Advanced

Let only the list decide the type

Write firstOr<T>(xs: T[], fallback: ...): T that returns the first item, or fallback when the list is empty.

Only xs should decide T. If xs is a list of "a" | "b", then firstOr(xs, "c") must be a type error, and firstOr(["a"], "z") must still work. Use NoInfer.

What Check tests

  1. Your code has no type errors
  2. The program prints a and z
  3. A fallback of another type is rejected
  4. A fallback outside the list's literal type is rejected
  5. A fallback of the same type is accepted
  6. The result keeps the list type

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.