Study notes · 10% of the exam

Everyday Types, Literals and Inference

Know how TypeScript infers and widens types, the difference between the top and bottom types, and when to reach for tuples, `as const`, `satisfies` or a union instead of an enum.

Key points

  1. 1

    A const holding a primitive literal gets the literal type ("hello"); a let and any object property widen to string, number and so on. as const stops widening, makes properties readonly and turns array literals into readonly tuples.

  2. 2

    any and unknown both accept every value, but unknown must be narrowed before use. never has no values and is assignable to everything; void means the return value should be ignored.

  3. 3

    {} accepts every value except null and undefined (primitives included); object accepts only non-primitives. Optional properties read as T | undefined.

  4. 4

    Tuples fix length and per-position types: optional elements make length a union such as 1 | 2, and a rest element makes it number. Mutable tuples still allow push, so prefer readonly tuples.

  5. 5

    Numeric enums emit an object with reverse mappings; string enums have none and are nominal. Since TS 5.0, out-of-range numeric literals are rejected. Unions of literals are erased entirely.

  6. 6

    Annotations replace the inferred type, satisfies validates while keeping it, and as overrides it (only between overlapping types). ! removes null | undefined and emits no runtime check.

  7. 7

    typeof x in a type position is a type query. keyof typeof SomeEnum gives the member names, and ${SomeEnum} gives the string values.

Common traps

  • const shape = { kind: 'circle' } gives kind: string, not 'circle'. The const protects the variable, not its properties.

  • A function declaration that always throws is inferred as returning void, not never. Annotate : never explicitly when you want control-flow narrowing after the call.

  • as and ! only change what the compiler believes. A wrong assertion still crashes at runtime.

Test yourself on Everyday Types, Literals and Inference

Ten questions, with the answer and explanation after each one.