Typescript Inference

Typescript Inference

variable declaration: const color
variable initialization: ‘red’

If declaration and initialization are on the same line, Typescript will figure out the type of ‘color’ for us.

But when are we going to add in these type Annotations?

If typescript can figure it out, why would we want to do it yourselves?

Try to use Type Inference.

But there are THREE scenarios where we rely on Type Annotations to help Typescript out.

Scenario 1 – ‘Any’ type

Whenever a function return the any type.

JSON.parse() –> ‘false’ –> boolean
JSON.parse() –> ‘4’ –> number
JSON.parse() –> ‘{“value”, 5}’ –> {value:number}

Can’t predict what we get in return.

So as a shortcut, typescript uses ‘Any’ type.
We have no idea what type gets returned.

type Any – means TS has no idea what this is – can’t check for correct property references

Avoid variables with ‘any’ at all costs.

The reason why is because say we have declare speed to be string:

if we then go

TS will let us know that property abcdef does not exist. Because TS knows that speed is a string.
But with Any, TS doesn’t know, and won’t be able to do this check for you.

Scenerio 2 – How to use Use Type Annotation to Fix the ‘Any’ Type

We can add type annotation for object.

Say we’re expecting an object where there’s a x and y property of type number.

Now if we mouse over coordinates, or try to access a weird random property, we’ll get proper feedback or error.

Delayed Initialization

Another way to add type annotation manually…

Scenario 3 – variable shows Type cannot be Inferred Correctly

what we could do: