Getting Started with TypeScript: Type Annotations & Type Inference (Part I)
Published: 2024-07-08 15:43:10

Type annotations and type inference are two different systems in typescript but in this post we will talk about them in parallel. 


## Type Annotations

**Code we add to tell TypeScript what type of value a variable will refer to**

_We tell typescript the type_


## Type Inference

**Typescript tries to figure out what type of value a variable refers to**

_Typescript guesses the type_

---

The type annotation system is kind of at odds with the type inference, so we are going to first understand type annotations and then come along and understand how type inference comes into play.

To make things a little bit more complicated, know that these two different features apply slightly differently to

1. Variables
2. Functions
3. Objects

Let's first talk about how they are applied to Variables, By Examples

```typescript
let apples: number = 5;
```
In this simple example **:number** is type annotation.

If we were to set the value of apples to a boolean we would get an error in  this case.

```typescript
const apples: number = true;
```
`Error: Type 'boolean' is not assignable to type 'number'.ts(2322)`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/umdgh57fvdwnjbj33ntr.png)

Similarly,

```typescript
let apples: number = 5;
apples = 'asdas
```

`Type 'string' is not assignable to type 'number'.ts(2322)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q617r9iwg7brxjwnvu6i.png)

```typescript
let banana = 5; // type inference
let banana: number // type annotation
let banana: number = 5 // type annotation
```

If the declaration and initialization are on the same line without type annotation, typescript will figure out the type of variable for us

 ```
[Variable declaration]      [Variable initialization]
     const        color   =               red
```

Objects:

```typescript
//Type inference
 let point = {
     x:10,
     y:20
 }

// Type annotation
let point: { x: number, y: number } = {
    x: 10,
    y: 20
}
```

Functions:

```typescript
//Type inference
const logNumber = (i) => {
    console.log(i)
}

// Type annotation
const logNumber: (i: number) => void = (i: number) => { // [(i: number) => void] is the annotation here
    console.log(i)
}
```

When to use annotations with functions

- Function that returns 'any' type
```typescript
const json = '{"x": 10, "y": 20}'
const coordinates = JSON.parse(json)
console.log(coordinates) // {x:10, y:20}
```

We need to understand how JSON.parse works for different values


| Passed Value      	| JSON.parse() 	| Return Value  	|
|-------------------	|--------------	|---------------	|
| 'false'           	| JSON.parse() 	| boolean       	|
| '4'               	| JSON.parse() 	| number        	|
| '{"value:5"}'     	| JSON.parse() 	| {value:name}  	|
| '{"name":"alex"}' 	| JSON.parse() 	| {name:string} 	|

_Typscript decides to set return type to any, meaning it has no idea what type will be returned._


## Why and when to use type annotation or type inference


#### Type inference


- When we declare a variable on one line then initialize it later
- When we want a variable to have a type that cant be inferred
- When a function returns the 'any' type and we need to clarify the value

#### Type inference


- Always
- When we  declare a variable on one line and initialize it later



Lets wrap the first part of type annotations and type inference in typescript. We will discuss it further in next post. 💯