Skip to content

Annotations and inference — when to write a type and when to let it be

Level: 101 · for anyone writing their first typed functions

Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.

One line: Inference types most variables unaided: let count = 1 is number, const one = 1 is the literal type 1, and a map callback's parameter is typed from the array; a declared function's parameters are not, and strict reports them as TS7006.

Keywords: type annotation, type inference, contextual typing

What the finished page will answer

  • What types does tsc infer for let count = 1, const one = 1 and [1, 2].map((n) => n * 2), and how can an error message be made to print them?
  • Why is a callback's n typed without an annotation while function half(n) gets TS7006?
  • When does an annotation change the type instead of repeating it: a variable assigned later, or a wider union such as let id: string | number = 1?
  • What does annotating a return type catch that inference lets through, for a function that forgets one branch?
  • What does const empty = [] get under strict, and why does tsc ask for an annotation with TS7034?

Examples it will need

  • annotations_inferred_types_tserror.ts — tsc's diagnostics revealing the inferred types of a let, a const and a map result, plus TS7006 for an unannotated parameter
  • annotations_return_type_tserror.ts — TS2366 for a function whose annotated return type exposes a branch that returns nothing

See also

Sources to start from