$TypeScript typing practice

Practice typing TypeScript generics, union types, and optional properties in a function that labels lookup results.

Start practice

Practice example

type Lookup<T> =
  | { value: T; label?: string }
  | { error: string };

function labelFor<T>(hit: Lookup<T>) {
  if ("error" in hit) return hit.error;
  return hit.label ?? "(untitled)";
}
Lookup<T>
Close the angle brackets after the type parameter, then switch to parentheses at the function signature.
| { error: string }
Start each branch of the multiline union with one pipe, using separate braces for each shape.
label?: string
Put the question mark before the annotation colon. The two question marks in the return line supply a fallback when the label is missing.

To type this example, paste it into Your code.