Type Annotation: a code that we add to tell the TypeScript compiler what type of value a variable will refer to.
annotation for primitives is simple and should be done like this
Type Inference: Typescript tries to figure out what type of value a variable refers to.
If variable declaration and initialization are on the same line typescript will figure out the type of the variable for us. If this happens in different lines or steps the TS compiler will set the type of the variable to any
What Is any Type?
If the TypeScript compiler is not able to type inference a variable it will set it to the type of any
that tells that the compiler has no clue at all what this variable type is.
we should avoid variables of any type at all costs because the main idea of TS is leveraging its type-checking system.
When To Use Type Annotations
- function that returns the type of
any
- then we need to interfere and define the type of the returned value In the following example see how we interfered and added a type to the coordinates object to prevent typescript from assigning it to any.
- Delayed initialization or when we declare a variable on one line and initialize it later.
- variable whose type can’t be inferred correctly