Harnessing the power of TypeScript Type Annotation and inference in our program.

Harnessing the power of TypeScript Type Annotation and inference in our program.

Towards debunking the myths around type annotation and type inference.

Type Annotations and Type Inference are two different concepts in TypeScript but would be discussed in parallel for a good reason.

To follow along, check the content overview below.

Screenshot (17).png This means our discussion will be based on Type Annotations and inference as applied to variables, Functions and Objects in TyepScript.

To begin, what is the difference between Type Annotation and Type Inference?๐Ÿค”

Type annotation is simply the little piece of code that tells TypeScript what type of value a variable will refer to. While Type Inference is when TypeScript tries to automatically figure out what type of value a variable refers to.

Screenshot (23).png Do you notice the similarity? Hmmm๐Ÿ™‚

Now, let's look at some Type Annotations in action as applied to variable declarations.

let apples: number = 5

In this case, the colon and the word after it before the assignment operator is the type annotation. The Type Annotation is telling TypeScript that we are only going to assign a value of type number to "apples". In this case, if we ever try to assign a value to apples that is not a number, we immediately see an error as shown.

Screenshot (13).png This is essentially telling us that the value we are trying to assign to the variable should be a number and not a string. hehe๐Ÿ˜ how smart.

Other primitive types can be shown as well.

let speed: string = "fast"
let nothingMuch: null = null
let nothing: undefined = undefined

Note: Do not use "const" for the variable declaration but instead use "let", since const does not allow variable reassignment.

Type annotations can be used with all the different types that TypeScript support such as

  • Primitive Types like number, string, boolean, symbol, void, null and undefined.
  • Object Types like Functions, Classes, Arrays and Objects.

How about built-in objects like Date? Well, the technique is the same.

Screenshot (25).png

// Built in Objects
let now: Date = new Date()

Let's try to write type annotation for a more complicated example like arrays. For an array of strings

let color: string[] = ["black", "blue", "green"]

For an array of numbers

let numbers: number[] = [1, 2, 3]

For an array of booleans

let truthFalse: boolean[] = [false, true, true]

This tells TypeScript that we are going to have an array(indicated by the square brackets) with either of the primitive types inside it. Simple right?๐Ÿ˜Š

So this is where we stop for today, watch out for the continuation of the discussion on type annotation and inference.

ย