Command Palette

Search for a command to run...

Hectal
Phase 8: Type Operators
TypeScript · Exercise 2 of 5 PreviousNext
Beginner

A getProp that can't be wrong

Write a generic function getProp(obj, key) that returns the property called key. The key must be a real key of obj, and the return type must be the type of that property.

Use <T, K extends keyof T> and the return type T[K]. Don't use any.

What Check tests

  1. Your code has no type errors
  2. The console prints Dune 412
  3. The result of getProp(book, "pages") is a number
  4. The result of getProp(book, "title") is not a number
  5. A key that isn't on the object is rejected
  6. No any in your code

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.