contextual typing
Type inference that flows from where a value is used, such as giving a callback's parameters the types the calling function expects.
In more detail
In items.filter((item) => item.price > 10), item gets the element type of items without any annotation. Event handlers passed to addEventListener likewise receive the right event type. This is why callbacks rarely need written types.
Related terms
- type inference — The compiler working out a type from the code itself, so you do not have to write it out by hand.
- callback — A function you pass to other code so it can call you back later, for example when an event happens or a timer fires.
- array methods — Built-in functions on every array, such as map, filter and forEach, that run a callback for each element.
- higher-order function — A function that takes a function as an argument or returns one, such as map, filter or a wrapper that adds retries.
Taught in
- tsconfig.json: target, lib, strict And NodeNext — Production TypeScript
- Type Annotations, Type Inference And Contextual Typing — Production TypeScript