DEV Community

Abhay Nikam
Abhay Nikam

Posted on

Day 4/100 - Type Annotations and Type Inferences in TypeScript

Sometimes it hard to sit on Saturday and fire up your laptop and work. You just wanna bail on it and relax. Still, I am very excited to learn TypeScript. So, today I learned Type Annotations and Type Inferences.

What are Type Annotations?

Type Annotations are the code added to tell TypeScript compiler that the value is of a particular type.

For example:

let name: string = "Abhay Nikam";
let hasName: boolean = true;

In the example above, we are telling TypeScript that the name is of type string. It should always refer to the string type. If we reassign it to another type, TypeScript will throw an error.

Try following in TS playground

let userName: string = "abhay";
userName = true;

What are Type Inferences?

Type Inferences is letting TypeScript figure out the type of value it refers to.

For example:

let name = "Abhay Nikam";

In the example above, TypeScript guesses what type of value name should refer to. Here it would be a string. If anything apart from string is reassigned to the name variable, TypeScript throws an error.

After understanding the differences and the definition of the Type Annotations and Type Inference, worked on trying to use them in code. Following is the usage of Type Annotations:

let name: string = "Abhay";
let age: number = 25;
let hasName: boolean = true;
let nothingMuch: null = null;
let nothing: undefined = undefined;

// Built-in objects
let now: Date = new Date();

// Array
let colors: string[] = ["Red", "Green", "Blue"];
let myNumbers: number[] = [1, 2, 3];

// Classes
class Car {}
let car: Car = new Car();

// Object literal
let coordinates: { x: number, y: number} = {
  x: 10,
  y: 20,

Happy Coding.

Top comments (0)