What is contextual typing in TypeScript?
When the type of an expression is applied by its location by TypeScript is known as contextual typing. Let us consider the following example:
window.onmousedown = function (mouseEvent) { console.log(mouseEvent.button); console.log(mouseEvent.foobar); // This is not allowed Property 'foobar' does not exist on type 'MouseEvent'. };
TypeScript type checker uses the type of the window.onmousedown
function to infer the type of the function expression.
It was able to infer the type of the mouseEvent
parameter, which contains a button property, but not a foobar property.