Lesson 3 of 10

Indexed access with keyof

Goal

A key that exists and a value of the right type

01

Explanation

If you have type User = { id: number; email: string }, then keyof User is the union of its key names, "id" | "email". Indexed access goes the other way: User["email"] is string.

Combine the two in a generic function like function getProp<T, K extends keyof T>(obj: T, key: K): T[K], and a key that doesn't exist becomes a compile error, while the result gets exactly the type of the field you asked for.

The common mistake is to write key: keyof T and make the result T[keyof T]. That's the union of the types of all the values, so the email's type becomes string | number. The second type parameter, K, is what remembers which key you passed.

02

Your task

Rewrite getProp without any, so it rejects keys the object doesn't have and its return type is the type of the requested field.

Checks

5 checks
  1. No type errors
  2. Returns the field's value
  3. The return type is exactly the type of the requested field
  4. A key that doesn't exist causes a compile error
  5. A numeric field can't be assigned to a string variable
03

Hints

0/3
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.