Functions in TypeScript

Description

Functions can be declared this way using TypeScript.

let greet: Function; //greet has been set to a function. Note that it has to be Function with a capital F.

greet = () => {
    console.log('helllo')
};
greet();

//specifying data types on paramters inside functions
const add = (a: number, b: number) => {
    console.log(a + b)
}
add(5, 1)

//parameters can be made optional by adding a question mark to it like this
const add = (a: number, b: number, c?: number | string) => {
    console.log(a + b)
}
add(5, 1)

//adding default parameters
const adds = (a: number, b: number, c: number | string = 'me') => {
    console.log(a + b)
    console.log(c)
}
adds(5, 12)
//always make the default parameter the last parameter to avoid a mix up when passing in the arguments.

const minus = (a: number, b: number) => {
    return a + b;
}
let result = minus(1, 5); //here the data type of the result variable will be the return value.

//the value of the return can be given a data type explicitly like this;
const minus = (a: number, b: number): number => {
    return a + b;
}
let result = minus(1, 5); //here the data type of the result variable will be the return value.

//a function in type script has the void value when nothing is returned.

No Comments Yet