Inference
Last updated
Last updated
Just as we normally declare and define variables in the same statement (e.g., let name = 'Jane';
), it's simpler to rely on the TypeScript transpiler to infer the variable's type from its initial assignment. In our example, name
is inferred to be of type string
because a string was assigned to it when the variable was delcared.
Likewise, when defining an object, you're better off leaving it to the transpiler to infer the types of its individual properties. (Though, depending on your requirements, it might make sense to use a or .)
The inferred type of a newly-defined array will be :
and when destructuring:
There is a compiler flag noImplicitAny
where the compiler will actually raise an error if it cannot infer the type of a variable (and therefore can only have it as an implicit any
type). You can then
either say that yes I want it to be an any by explicitly adding an : any
type annotation
help the compiler out by adding a few more correct annotations