in the world of TypeScript, every assignable value has a type (as discussed in the last blog). Now to identify what type of a certain value has we have Type Annotations and Type Inferences.
1️⃣Type Annotations -
Type Annotation at its core is just a small amount of code that we write to tell TypeScript what type of value a variable will refer to.
So we developers tell typescript what types of values we are working with.
Example of Type Annotations
Type Annotation with variables
const numCars: number = 5;
so the :number
is our Type Annotation, now this tells typescript that we are only going to assign a type of number to numCars variable, and if we try to assign any other type we will quickly see an error.
more examples of Type Annotation with different types are :
let speed: string = 'fast';
let isSuperCar: boolean = false;
let sunroof: null = null;
let nothing: undefined = undefined;
const todayDate: Date = new Date();
2️⃣Type Inference -
Type Inference just simply is a way in which typescript tries to find out what type a value is going to have.
the general example of type inference with variables looks like this :
let isSuperCar = false;
now if we try to assign a value that is not a boolean we will see an error.
if we see in the error typescript has identified what type of value isSuperCar
has even though we have not told that typescript what type isSuperCar is going to have.
3️⃣When to use Type Annotation and Type Inference -
When to use Type Annotation:
- When we have a variable whose variable can't be inferred, suppose we have a variable which can either have a boolean or a number value. In that case type inference will not be able to identify the type of variable on its own, the we need type inference an the syntax looks like this :
//A car can either have one sunroof or none
let sunroof: boolean | number = false;
//Now if we assign it a value of 1, we will not get an error
sunroof = 1;
//It will not give an error as we have annotated that it is going to have either a boolean or a number as a value
When we declare value on one line and initialize it later,
earlier type inference worked because we had the declaration and initialization on the same line.When a function returns the 'any' type in that case we need to clarify the value beforehand.
When to use type inference -
Except for the above corner cases, we always try to rely on type inference.
In the next blog we will see more examples revolving around Type Annotation, Type Inference, and the corner cases
Top comments (0)