TypeScript Functions and Classes

on May 31, 2020 · 2 mins read

Function is a block of code that works to fulfill a certain task. Itusually takes in input(not necessarily) and produces output producing result.

Differing from JavaScript, TypeScript needs return type of the function to be declared.

Example function to add two numbers:

	
	function add(a: number, b:number):number{
	return a+b;
	}
	let result1=add(3,5);
	console.log(result1)

let’s modify result1 by:

let result1=add(3)

We can see that we get error expected two arguments but got 1.

We change this by modifying the parameter declaration as:

function add(a: number, b?:number):number

So now we get the result but it’s not a number(NaN). With compatible types say:


	function add(a: string, b:string):number{
	return a+b;
	}
	let result1=add("Mark","Hughes");
	console.log(result1)

let’s modify result1 by:

let result1=add(3)

Write a function to calculate the average of three numbers  12,28,150. Demonstrate function calling as well.

	
	function averageFinder(firstNum:number, secondNum:number, thirdNumber:number){
	return (firstNum+secondNum+thirdNum)/3;
	
	}
	
	console.log(averageFinder(12,28,150))

Classes in JavaScript

Classes are what makes TypeScript different from JavaScript. Classes are the main feature behind the object oriented language.


class DoubleNumber {
    randomNum: number;
    constructor(num: number) {
        this.randomNum = num;

    }
    doubleValue() {
        return this.randomNum * 2;
    }

}
let someNumber = new DoubleNumber(3);
console.log(someNumber.doubleValue())

Constructors

Class is like a blueprint for “objects”. Car is a class. Honda Civic is an object. Cars have certain features like engine hp, fuel efficiency, fuel type that makes it a car. So, classes have everything necessary to instatiante an object. Lamborghini is an obect of class Car.

While instantiating a object, you can create also create a new object by using parameters like in function. Those are called parameterized constructors. For that a special function called a constructor in the class is required. Constructor allows the setting of the member variables(variables that are member to some methods, class, etc.)

Write a program to find the perimeter of a circle implementing classes(perimeter=23.14radius).


class Shapes {
    radius: number;

    constructor(num: number) {
        this.radius = num;
    }

    findPerimeter(): number {
        return 2 * 3.14 * this.radius;
    }

}
let circle = new Shapes(5);
console.log(circle.findPerimeter())