Guess the type TypeScript infers: 8 levels of narrowing, conditional types and template literal types. A TypeScript inference 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.
nama can be a string, or null. If it is null, the function goes home. What type is nama on the marked line?nama on the marked line?h can be a Kucing or an Anjing; jenis tells them apart. What type is h inside the if?unknown). The function isString promises: if it answers true, the contents are a string. What type is isi inside the if?as const. What type is giliran?ulang returns exactly the word that goes in. What type is jawab?ReturnType takes the type the function returns. What type is Saldo?kopi. A conditional type is a gate inside the type system: does every string fit in 'kopi'? What type is Cocok?tamu on the marked line?