Monday, September 23, 2024
Google search engine
HomeLanguagesJavascriptHow to write a function in Typescript ?

How to write a function in Typescript ?

Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.

Syntax: Let’s see a basic TypeScript function syntax (with two arguments)

function functionName(arg1: <arg1Type>, 
        arg2: <arg2Type>): <returnType> {
    // Function body...
}

Below are some functions to help better understand.

Example 1: In this example, we are writing a function to add two numbers
 

Javascript




// TypeScript Code
// Following function returns the addition
// of it's two parameters
function addTwo(a: number, b: number): number {
    return a + b;
}
 
console.log(addTwo(7, 8)); // logs 15


Output:

15

Example 2: Add two numbers and return equivalent hexadecimal string.

Javascript




// Following function adds it's two parameters then
// returns it as string form in base 16
function getHexAddition(a: number, b: number): string {
    return (a + b).toString(16);
}
 
console.log(getHexAddition(10, 16)); // logs '1a'


Output:

1a

Adding Optional and Default Parameters: Adding an optional parameter is super simple, just add ? to the end of the argument name.  

Example 3: Write a function that logs a Good Morning message with a name, if a name is not passed then logs only Good Morning.

Javascript




// Following function returns good morning
// message based on value of name passed
function goodMorning(name?: string): string {
    
    // if name exits use it as suffix else ignore name
    const suffix = (name ? `, ${name}.` : '.');
    return 'Good Morning' + suffix;
}
 
// logs 'Good Morning.'
console.log(goodMorning());
 
// logs 'Good Morning, Sam.'
console.log(goodMorning('Sam'));


Output: For default argument suffix it with an equal sign and default value (TS compiler will automatically deduce the type for default argument based on provided value).

Good Morning.
Good Morning, Sam.

Example 4: Write a function that returns the base^{power}, if power is not provided then it is assumed to be 1.

Javascript




function pow(base: number, power = 1): number {
   return Math.pow(base, power);
}
 
console.log(pow(7));    // logs 7
console.log(pow(7, 2)); // logs 49


Output:

7
49

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments