Type Annotation VS Type Inference
The differences and applications

Blog Post by Derrick Madumere - Published at 5/10/2023, 11:09:37 AM
Introduction
Are you curious about typescript and its features? In this article, we will be discussing the difference between type annotation and type inference in typescript in a more friendly and approachable way.
What is type annotation?
- Type annotation is the explicit assignment of a variable, function arguments, or function returns to a specific type.
- By doing this, we are telling typescript what the value type should be throughout the lifecycle of that variable.
- Typescript will ensure that the type of the variable does not change, and if there is an attempt to change it,
- typescript will either place a red squiggly line under the variable during development or throw an error during compilation.

For example, if we declare a variable 'age' and assign it the value of 20, we can explicitly tell TypeScript that 'age' is of type number. We do this by adding a colon followed by the type of the variable:

If we attempt to reassign 'age' to a different value type, TypeScript will indicate that we are doing something wrong with a red squiggly line in the code, and hovering over it, we get the error "Type 'string' is not assignable to type 'number'".

If we go ahead to compile this code, the compiler will let us know there is an issue even if the code still gets compiled.

What is type inference?
- Type Inference is the system that allows typescript to guess the value type of a variable after it has been declared and initialized.
- Typescript is smart enough to tell what type a value is and we don't always need to explicitly state the value type of a variable.
- Typescript can correctly infer the value type if the variable declaration and variable initialization happen on the same line;
- otherwise, it will consider the variable as type 'any'.
For example, we can declare a variable 'pet' and assign it the value of "dog". Typescript will automatically infer that the value type of 'pet' is a string without any type annotations.

If we try to reassign a different value type to 'pet', TypeScript will let us know that we are doing something wrong.

Without the variable declaration and initialization done on the same line, typescript automatically assigns the variable the "any" type value.

- It is important to note that with type inference, typescript will not enforce type checking on variables with type 'any'.
- As such, these variables with 'any' value type can be reassigned to different value types during their lifecycles.
Conclusion
- Type annotation and type inference are both important features in TypeScript that help developers write more robust and error-free code.
- Type annotation is explicit and requires you to specify the type, while type inference is implicit and allows typescript to automatically infer the type based on usage.