Skip to content
Related Articles

Related Articles

How to write a function in Typescript ?

Improve Article
Save Article
  • Last Updated : 09 Aug, 2021
Improve Article
Save Article

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


// 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



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


// 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'



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.


// 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.'
// logs 'Good Morning, 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.


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




My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!