Open In App

How to call Typescript function from JavaScript ?

Last Updated : 22 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand all the facts which are associated with how we may call typescript function from JavaScript. TypeScript supports the existing JavaScript function syntax for declaring and calling it within the program or the code snippet. Let us quickly understand how we may declare a function in TypeScript.

Syntax for declaring TypeScript Function: Following syntax we may use to declare any function in TypeScript-

function function_name (parameter_name : data_type, ...) : return_type {
    // Do something.....
}

Now that we have seen the syntax of declaring a typescript function let us quickly jump into the part of the following example where we will see how we call the typescript functions, which we are going to declare in a while, using the similar manner as we do by following a certain syntax in JavaScript-

Example 1: In this example, we will simply implement a function that will print the sum of two numbers upon calling. This is the simplest example we are taking into account in the beginning. Moreover, we will be using the arrow function in this example itself.

Javascript




let sumOfNumbers = (
    firstnum : number, 
    secondnum : number
) : number => {
    return firstnum + secondnum;
}
  
console.log(sumOfNumbers(4 , 5));
console.log(sumOfNumbers(15 , 19));


Output:

9
34

Example 2: In this example, we will try to implement a typescript function that will accept its data from the statically typed object (a feature provided by TypeScript wherein we may declare an object using type before the name of the object), and thereafter we will use the data to actually print the data of a user.

Javascript




type userDetails= {
    firstName: string;
    lastName: string;
};
    
let displayUserName = (userDetail : userDetails) => {
    return "Name of the user is : " 
    + `${userDetail.firstName} ${userDetail.lastName}`;
}
    
let user : userDetails= {
    firstName: "ABC",
    lastName: "DEF"
};
    
let userName = displayUserName(user);
console.log(userName);


Output:

Name of the user is : ABCDEF


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads