Quick Guide to Typescript - Part 1

Quick Guide to Typescript - Part 1

Let's get started with some quick guide to Typescript.

📌 Introduction

  • Typescript is superset of Javascript which means it is an extension of Javascript, adding new features and syntax on top of the core language.
  • Typescript is a strongly typed, object-oriented & compiled language.
  • Typescript is designed to be compiled into fully compatible Javascript, so it works in any browser, any host, and any OS.
  • We need typescript compiler to compile it to Javascript code because browsers do not understand typescript.
  • Typescript strongly encouraged static-typing which means it will validate all the assertions before the code executes. It allows you to do a type check during development which leads to the cleaner code and less errors in the browsers.

If you are familiar with Javascript, then you know that javascript is a dynamic language:

// In Javascript

const logger = (msg) => console.log(msg);

let marks = 20;

logger(marks);   // output: 20

marks = 'twenty';

logger(marks);  // output: twenty

In the above code as you notice first we assign a value of type number to variable marks and then reassign it value of type string to the same variable.

This is possible in javascript because it is weekly-typed language which means the type of variable is figured by JS at runtime & can be change from one type to another.

But this is not the case with typescript.

Let's get familiar with some unique feature which typescript provides :-

📌 Type Inference

Typescript uses inference or it infers the type based on the value we assign to it.

let age = 20;

age = 'twenty';  // ERROR
age = 40;  //CORRECT

In the above code snippet, when we try to assign a value of type "string" to variable age, it will cause error. But why???

In Typescript, we can change the value of variables but not the type.

When we first assign a value to variable age, we don't have to specially mention the type of the variable, typescript infer its type as number, which cannot be change later.

🧩 Functions

  • We can also declare what type of a value we are expecting to be passed into the function as an arguments.
const area = (diameter: number) => {
    return diameter * Math.PI

area(2); //Correct
area('two'); // ERROR

🧩 Arrays

let marks = [100, 200, 300, 400, 500];

// marks.push('abc'); //ERROR

In the above code snippet, typescript infers the type of array marks as "number", hence we cannot insert a value of type "string" into it.

There is another case:

let mixed = ['xyz', 0, 3];

mixed[1] = 'abc';  //Correct
mixed[0] = 5;  //Correct
mixed[3] = true; //ERROR

In above code, typescript infers the type of array "mixed" as number or string, so we can insert the values of these types only, so in above case value of type boolean is not acceptable.

🧩 Objects

  • Once we define the object we cannot assign additional properties to it later on.
let student = {
    name : 'xyz',
    marks: 30

student.marks = 100;
student.marks = '30' //ERROR

//Cannot assign new property to an object
student.age = 10 //ERROR
  • Once we declare an object then it has to have a same structure, the same type with the same set of properties which cannot be changed later on except the values.

📌 Explicit Types

  • Typescript uses inference to know the type of the variable but we can also explicitly define the types using the following syntax:
// Explicitly defining the types of variables
let character: string;
let totalMarks: number;
let isloggedIn: boolean;

totalMarks = '200'   //ERROR

🧩 Arrays

// this array will contain elements of type string
let studentList: string[ ] 

// this array contains element of type number & also initialising it with empty array
let studentMarksList: number[ ] = [ ]

🧩 Objects

//Method 1
let bucketList : Object; 

bucketList = {
    name: 'apple',
    price: 30

//Method 2
let bucketList2: {
    name: string,
    price: number

📌 Union Types

In typescript, union type allows us to define a variable with multiple type.

In case you want to explicitly define an array which can contain elements of type string or number, then the syntax for the same would be:

let mixedList: (string | number)[] = [];

// mixedList.push(true); //ERROR

Following the same rule for other variables as well

let uid : string|number;
uid = 'acc';
uid = 10;
// uid = false; //ERROR

📌 Dynamic Types

There are times when we are not sure of the exact type of specific variable. In this scenario typescript provides special type: any. This allows you to assign "any" value to that variable.

let list : any;

list = 10;
list = 'abc';

let countList : any[] = [];

📌 Functions in Typescript

  • In Typescript we can either use an arrow functions or a regular functions.
let greet: Function
greet = () => {
    console.log("hello world");

const add = (a:number, b: number) =>{
    console.log("sum = ", a + b);

  • you can define optional parameter inside a function using the syntax:
const subtract = (x: number, y: number, z?: string|number) =>{
    console.log("difference-> ", x-y);
    console.log("optional parameter-> ", z );

subtract(10, 5);
subtract(20, 10, 30);
subtract(100,50, 'abc');

Always put your required parameters at first and then put the optional parameters at the end.

  • define default value of a parameter inside a function :
const multiply = (x: number = 10) =>{
    console.log("default value parameter-> ", x );

multiply(); // 10
multiply(20); //20
  • When a function returns something, typescript will infer the return type automatically.
const divide = (x: number, y:number)=>{
    return x/y;

//Typescript automatically infer the type of result as number
const result = divide(20,10);
  • You can also explicitly define the return type of function by using the syntax:
const msg = ():string =>{
    return 'hello world';

const greeting = msg();
  • function in Typescript will return a void value when function doesn't return something. void is completely different from undefined in javascript.
// Function Signature
let calculateFn: (x: number) => void 

calculateFn = (num: number) => {
    console.log("num-> ", num)


📌 Type Aliases

We can initially defined the type which can be reusable later on with the keyword type.

type stringOrNumber = string | number;
const myPredefinedType: stringOrNumber = 10;

type personRecord = {
    name: string,
    marks: stringOrNumber

let obj : personRecord;
obj = {
    name: 'anu',
    marks: '100'

In the above code snippet, we have define two types stringOrNumber & personRecord, which are reused later on.

📌 Wrap Up!!

That's all for this article. We'll explore more new features of typescript in the next post. Thank you for your time!! Let's connect to learn and grow together.

LinkedIn Twitter Instagram