Functions

Docs

Example

Define parameters & return type

function add(x: number, y: number): number {
return x + y;
}
function sendEmail(to: HasEmail): { recipient: string; body: string } {
return {
recipient: `${to.name} <${to.email}>`, // Mike <mike@example.com>
body: "You're pre-qualified for a loan!"
};
}
//in the above case return type can also be inferred by TS
//(always hover the variable/ function to check inferred type)
Arrow functions
const add = (x, y) => {
return x + y;
}
const add = (x: number, y: number): number => {
return x + y;
}
Rest param example
const sum = (...vals) => {};
const sum = (...vals: number[]) => {};

Function param

(Shape of the object example)

Consider

interface Address {
houseNumber: number;
streetName: string;
}
function validateHouseNumber(obj:{houseNumber:number}){
}
let myAddress: Address = {
houseNumber: 20,
streetName: 'dream street'
}
validateHouseNumber(myAddress); //is valid as target param shape is present

Function overloading

(TS_SPECIFIC*)

Usage: When we want to allow a set of parameter combinations only

function addRows(x: string[]): number[];
function addRows(x: string): number;
function addRows(x:any): any {
if (typeof x == "string") {
return 1;
}
else {
return [1,2,3];
}
}

function overload

Instead of any , can use particular OR condition, so that we get intellisense within that function

function addRows(x: string[]): number[];
function addRows(x: string): number;
function addRows(x:string[] | string): number[] | number {
if (typeof x == "string") {
return 1;
}
else {
return [1,2,3];
}
}