TypeScript has a powerful type inference system. In most cases, the types of variables, parameters, and return values are automatically calculated based on context. There are several levels of type inference:
Examples:
let a = 2; // number let b = [1, "a"]; // (number | string)[] window.addEventListener('click', e => { // e: MouseEvent });
Limitation: if the compiler cannot unambiguously infer the type — it will choose the broadest type (usually any), which negates the benefits of typing.
Is the function argument typed if not explicitly specified, but the function is later used with a typed value?
Wrong answer: Yes, TypeScript will always automatically "guess" the argument type.
Correct answer: No. Only if the function context contains type information will the argument be typed. Otherwise, it will be any or another basic type, leading to errors. It's always a good practice to explicitly type input data.
Example:
function f(x) { return x.toFixed(2); // Error: x is of type any }
Story
In a project, the return type of a custom React hook was not explicitly specified, and TypeScript did not see that the type could be
undefined. As a result, calling a method on an object without a check led to runtime errors.
Story
When creating an array of mixed-type values, the final type was automatically inferred as an
any[]array because a type was not explicitly specified, which led to the loss of all typing benefits in the subsequent code.
Story
The validation of service input parameters was not typed and relied on TypeScript's "guessing". After refactoring the codebase, automatic inference resulted in too broad a type, and data type errors made it to production.