Type Promise — TypeScript

Guess the type TypeScript infers: 8 levels of narrowing, conditional types and template literal types. A TypeScript inference game.

What you learn in this game

TypeScript reads code like a road. After if (x === null) return, the null possibility has left the function, so on the next line the type of x narrows. This is called narrowing.

Narrowing only happens when the code checks the value. Without a check, the type stays as the parameter says, and TypeScript refuses .length on a value that may be undefined.

A discriminated union: every member has the same property (jenis) with a different literal value. Checking that value tells TypeScript which member is inside the block.

A type predicate (x is T) is a function's promise: if it returns true, the value has type T. TypeScript uses that promise to narrow the type inside the if, even from unknown.

as const is a seal: TypeScript does not widen the value. An array becomes a readonly tuple, each element typed as the exact literal written.

A generic with a bound (T extends string) makes TypeScript infer T from the argument. A literal argument "a" makes T "a", and if the function returns T, the result is "a" too.

What the levels ask

  1. Nenek Marni greets the guests who come. nama can be a string, or null. If it is null, the function goes home. What type is nama on the marked line?
  2. Bagas measures the length of each player's name for his scoreboard. Players may leave the name empty. What type is nama on the marked line?
  3. Rara opens her yard gate for cats only. h can be a Kucing or an Anjing; jenis tells them apart. What type is h inside the if?
  4. Mbak Wulan receives a parcel whose contents are unknown (unknown). The function isString promises: if it answers true, the contents are a string. What type is isi inside the if?
  5. Pak Tono and Nenek Marni have shared the paddy water at the same hours for thirty years: six and eighteen. Pak Tono seals the schedule with as const. What type is giliran?
  6. Bu Guru Ratna takes the roll call. The function ulang returns exactly the word that goes in. What type is jawab?
  7. Mas Bayu works out a balance with an async function. ReturnType takes the type the function returns. What type is Saldo?
  8. The wi-fi password at Kak Piksel's warnet is kopi. A conditional type is a gate inside the type system: does every string fit in 'kopi'? What type is Cocok?
  9. Pak Harun waits for the last passenger at the terminal. Nobody knows yet who it is. Not an animal: home; a cat: home. What type is tamu on the marked line?