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 = 1and[1, 2].map((n) => n * 2), and how can an error message be made to print them? - Why is a callback's
ntyped without an annotation whilefunction 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 understrict, 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 alet, aconstand amapresult, 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¶
- Primitive and literal types — why
constinfers1andletinfersnumber - Generic functions — inferring type parameters from the arguments
- When inference guesses wrong — when you must write the type argument yourself
satisfies,asand annotations — the three ways to state a type, compared- Rust: Type inference ↗ — in Rust, inference also uses later lines; TypeScript uses the initialiser
- Rust: What a type annotation does ↗ — an annotation as an input to inference, in Rust