A quick guide on TypeScript

Dhruv Saksena
3 min readJun 13, 2021

I spent last week on learning Typescript and the way I look at it is that in true sense it’s just to make the lives of Javascript developers little better… :).

Javascript is dynamically typed language. It offers a great level of flexibility but at the same time, one gets to know about the errors only at the runtime. Typescript just fills this gap as it’s a statically typed language. Many of the errors which in case of Javascript one gets at runtime, can be easily caught at the compilation stage. It has it’s own tsc compiler which compiles this into a javascript code. Also, you can fine tune the compiler with hell lot of options available tsconfig.json.

If you are familiar with Javascript, the below article gives quick example on how to get started with Typescript.

  1. Declaring data-type in function
function add(n1:number, n2:number)
{
}

2. Declaring data-type in code

let salary: number = 2300;
let favActivities: string[];
favActivities = ["Dhruv"]

3. Declaring Object-Type

const person: {
name: string;
age: number;
dept: string;
}
= {
name: "Dhruv",
age: 36,
dept: null
};
console.log(person.name);

4. For loop in typescript

const person: 
{
name: string;
age: number;
dept: string;
hobbies: string[];
} = {
name: "Dhruv",
age: 36,
dept: "Tech",
hobbies: ["Coding","Designing"];
for(const hobby of person.hobbies)
{
console.log(hobby.toUpperCase());
}

5. Declaring Enums

enum Role {ADMIN,READ_ONLY,AUTHOR};
const person: {
name: string;
age: number;
dept: string;
hobbies: string[];
role: Role;
} = {
name: "Dhruv",
age: 36,
dept: "Tech",
hobbies: ["Coding","Designing"],
role: Role.ADMIN
};
console.log(person);
for(const hobby of person.hobbies)
{
console.log(hobby.toUpperCase());
}
if(person.role === Role.ADMIN)
{
console.log("Person "+ person.name + " is an admin");
}

6. Union operator in TypeScript

function combine(input1: number | string, input2: number | string)
{
let result;
if(typeof input1 === 'number' && typeof input2==='number')
{
result = input1 + input2;
}
else
{
result = input1.toString() + input2.toString();
}
return result;
}
console.log(combine(30,35));
console.log(combine("Hello","Hii"));

7. Custom Type in Typescript

type Combinable = number | string;
function combine(input1: Combinable, input2: Combinable)

{
let result;
if(typeof input1 === 'number' && typeof input2==='number')
{
result = input1 + input2;
}

else
{
result = input1.toString() + input2.toString();
}
return result;
}
console.log(combine(30,35));
console.log(combine("Hello","Hii"));

8. Defining Function-types

function add(n1: number, n2:number): number
{
return n1 + n2;
}
function printResult(num: number): void
{
console.log("Printing result:: " + num);
}
let fnToBeCalled: Function = add;
console.log(fnToBeCalled(3,4));

9. Function Type in function

function greet(name: string): string
{
return "Hello " + name;
}
let greetFunction: (name: string) => string;
greetFunction = greet;
console.log(greetFunction("Dhruv"));

10. Function Type in CallBack function

function addAndHandle(num1: number, num2: number, cb: (num: number)=>void)
{
cb(num1 + num2);
}
addAndHandle(10, 30, (result: number) =>{console.log("Result is:: "+ result);});

11. Initializing typescript compiler to a project

tsc --init

12. Exporting objects

import dotenv from 'dotenv';
dotenv.config();
const SERVER_HOSTNAME = process.env.SERVER_HOSTNAME || 'localhost';
const SERVER_PORT = process.env.SERVER_PORT || 3000;
const SERVER = {
hostname: SERVER_HOSTNAME,
port: SERVER_PORT
}
const config = {
server: SERVER
}
export default config;

Here, dotenv is a library which holds the environment configuration in a .env file. Once, we have configured the environment in the file then we can use process.env.ENVIRONMENT_VARIABLE within our application.

13. Declaring classes in Typescript

export default class Invoice
{
client: string;
details: string;
amount: number;
constructor(_client: string, _details: string, _amount: number)
{
this.client = _client;
this.details = _details;
this.amount = _amount;
}
format(): string
{
return `${this.client} owes me ${this.amount} with ${this.details}`;
}
}

14. Using classes to construct Objects

import Invoice from './classes/Invoice';
const invoice = new Invoice("Dhruv","For burger", 300);
const invoice2 = new Invoice("Hello", "No reqd", 700);
let invoices: Invoice[] = [];
invoices.push(invoice);
invoices.push(invoice2);
invoices.forEach(inv => {
console.log(inv.client, inv.details, inv.amount, inv.format());
});
console.log(invoices);

15. Declaring arrays

const topic: string[] = ['reviews'];

16. Importing modules in typescript

There are two ways to import modules in Typescript-

One when we want to import all functions of the module-

import * as BodyParser from 'body-parser';
//usage
BodyParser.json()

Another is when we want to import specific functions from a module and use them directly-

import {json, raw} from 'body-parser';
//usage
json()

17. Promises in Typescript

Here, is a sample code using which one can use promises in Typescript.

import "isomorphic-fetch";fetch("http://google.com")
.then( (response) => {
console.log("Response is:: "+ response.status);
})
.catch( (reason) => {
console.log("Reason is:: "+ reason);
})
.finally( () => {
console.log("END");
});

--

--

No responses yet