Typescript expression function
Created By: chatGPT
TypeScript provides a powerful way to define functions using expression syntax. An expression function can be created using arrow functions, which offer a more concise syntax and maintain the context of
this
. Here’s how you can define an expression function in TypeScript.const add = (a: number, b: number): number => {
return a + b;
};
The above function
add
takes two parameters, a
and b
, both of type number, and returns their sum. Arrow functions are particularly useful for when you need to maintain the this
context naturally.const multiply = (a: number, b: number): number => a * b;
For single-line functions, you can omit the braces and the
return
keyword. In this case, the function multiply
multiplies two numbers without explicit return statements.const logResult = (result: number): void => console.log(`The result is: ${result}`);
In TypeScript, you can also specify the return type. For instance, the
logResult
function takes a number and returns void, meaning it does not return any useful value, but instead performs an action like logging the output to the console.const getGreeting = (name: string): string => `Hello, ${name}!`;
This
Here, the getGreeting
function takes a string parameter name
and returns a greeting message as a string. Type inference in TypeScript means that if you do not specify the return type, TypeScript will try to infer it automatically.const square = (x: number): number => x * x;
square
function takes a number x
as an input and returns its square. This shows how TypeScript can help enforce types on our functions, leading to more robust and maintainable code.