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
function addTwo(a: number, b: number): number {
return a + b;
}
console.log(addTwo(7, 8));
|
Output:
15
Example 2: Add two numbers and return equivalent hexadecimal string.
Javascript
function getHexAddition(a: number, b: number): string {
return (a + b).toString(16);
}
console.log(getHexAddition(10, 16));
|
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
function goodMorning(name?: string): string {
const suffix = (name ? `, ${name}.` : '.' );
return 'Good Morning' + suffix;
}
console.log(goodMorning());
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));
console.log(pow(7, 2));
|
Output:
7
49
Last Updated :
09 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...