- How To Set The Return Type Of A Arrow Function In TypeScript
- Set the return type of a arrow function in TypeScript
- Use colon
- Some common error case
- Use with the union type
- Summary
- How Does An Arrow Function Work In TypeScript?
- The definition
- The syntax
- Difference between an arrow function vs. a regular function
- How to return an object from an arrow function?
- How to set the return type of an arrow function?
- How to define an arrow function in a class?
- Final thoughts
How To Set The Return Type Of A Arrow Function In TypeScript
Knowing how to set the return type of a arrow function in TypeScript will be very important to explicitly set the type for an arrow function and also help you easy to write and maintain code. So how to do it?Let’s go into detail.
Set the return type of a arrow function in TypeScript
Use colon
You can set the return type of an arrow function in Typescript by specifying the type after the colon between the bracket and the arrow.
const anFuction = (): string => < return "Hello From Learn Share IT"; >; console.log(anFuction());
[LOG]: "Hello From Learn Share IT"
As you see here, I set the string type for the returnLog arrow function by using a colon between the round bracket and the arrow symbol.
Some common error case
If you set the return type of an arrow function, you will get the error if you did not set the return type.
const returnNumber = ():number=> < // Return 'Hello From Learn Share IT' >console.log(returnNumber())
A function whose declared type is neither 'void' nor 'any' must return a value.
Here I get the error because I make sure that my arrow will return the type number, so it must be. If I do not return anything, the return arrow function will be void which means I do not return any value and I get the error.
Or if you set the return type of the arrow function to this type, but in execution, the arrow function returns another type, it also leads to an error.
const returnLog = (): string => < return 9; >; console.log(returnLog());
Type 'number' is not assignable to type 'string'.
Here number nine is the number type, but I set the return type of the arrow function as a string, and it will lead to an error.
Use with the union type
If you are not sure what the return type is, you can use the union type.
const returnValue = (val: string | number): string | number => < return val; >; console.log(returnValue("Hello From Learn Share IT")); console.log(returnValue(8));
[LOG]: "Hello From Learn Share IT" [LOG]: 8
Here I set the return type that can return both string and number type values.
Or you can use any type. It will make your arrow function can return any type.
const returnValue = (val: any): any => < return val; >; console.log(returnValue(< name: "Toan" >)); console.log(returnValue([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
[LOG]: < "name": "Toan" >[LOG]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Summary
In this article, I showed you how to set the return type of a arrow function in TypeScript. You can set the return type after the colon between the bracket and the arrow symbol. I also show you some common cases when you set the return type of an arrow function. Hope it is helpful to you.
Maybe you are interested:
Hello, guys! I hope that my knowledge in HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, Python, MySQL, and npm computer languages may be of use to you. I’m Brent Johnson, a software developer.
Name of the university: HOU
Major: IT
Programming Languages: HTML, CSS, JavaScript, TypeScript, NodeJS, ReactJS, MongoDB, PyThon, MySQL, npm
How Does An Arrow Function Work In TypeScript?
Nowadays, an arrow function is the default and easiest way to define a function in TypeScript and JavaScript. But how does it work exactly?
Here is an example of an arrow function in TypeScript:
typescriptconst sum = (x: number, y: number): number => x + y;
This article explains how arrow functions work in TypeScript and shows many code examples.
The definition
Initially introduced in ES6, arrow functions allow developers to write functions with shorter syntax.
They are sometimes called lambda, fat arrow, or anonymous functions.
We do not need to use the function keyword when defining an arrow function.
They are many reasons to use the arrow function.
- Shorter and more straightforward syntax.
- Lexical scoping of this keyword.
- Lexical capturing of arguments .
You can use default parameters with arrow functions if you need to set default values for the function’s parameters.
In TypeScript, arrow functions can also be generic. A generic arrow function can accept any argument type and allows developers to create more reusable components.
Arrow functions also allow developers to use the quick object return.
The syntax
Here is the syntax of an arrow function:
typescript(param1, [ . paramN ]) => expression
The syntax of the arrow function contains three parts:
- The parameters that the function may or may not have.
- The arrow notation.
- The expression which represents the function’s body.
The best Web Development course in 2023! 👉 Learn Web Development
Difference between an arrow function vs. a regular function
Both are valid ways to define functions in TypeScript and JavaScript. However, they have significant differences.
The most obvious difference is their notation:
typescript// Function expression const output = function (str: string): void < console.log(str); > // Arrow function const output2 = (str: string): void => < console.log(str); >
The most significant difference between an arrow and a regular function is their execution context ( this ).
- Inside a regular function, the this value is dynamic. It means that its value depends on how the function is invoked.
- Inside an arrow method, the this value always equals the outer function, making it easier to understand.
Other differences include:
- Arrow methods cannot be overridden inside a child class, but regular functions can.
- Arrow functions cannot be called using the new keyword, but regular functions can.
- Arrow functions provide support for implicit return, and regular functions don’t.
How to return an object from an arrow function?
Arrow functions allow returning an object literal without using the return keyword. To do a quick object return, surround the object literal with parentheses.
typescriptinterface IAnimal < name: string; type: string; > const getAnimal = (name: string, type: string): IAnimal => (< name, type >);
P.S. Quick object return only works when the arrow function only contains a return statement.
How to set the return type of an arrow function?
The return type of an arrow function is set the same way as for a regular function. The developer needs to define the return type explicitly or let the TypeScript compiler infer the return type.
typescriptinterface IPerson < name: string; age: number; > const getPerson = (name: string, age: number): IPerson => (< name, age >);
In this example, the getPerson function returns the IPerson interface.
How to define an arrow function in a class?
In TypeScript, you can define an arrow function inside a class as a property.
typescriptclass Dog < public constructor( private name: string ) < >eat = (): void => < console.log(`$this.name> is eating.`); > > // Outputs: 'Flappy is eating.' new Dog('Flappy').eat();
In this example, we define the eat function as a class property.
An arrow method inside a class is useful when using the function as a callback. Property methods pass the correct context to the function. Otherwise, you need to bind this to the function.
Note: Here we are using string interpolation to concat the strings.
Final thoughts
As you can see, arrow functions are simple to use in TypeScript.
Most of the time, I recommend using arrow functions unless:
- You are using a library like jQuery that uses the dynamic context of this .
- You want to use arguments .
- You want to use object methods.
Here are some other TypeScript tutorials for you to enjoy:
The best Web Development course in 2023! 👉 Learn Web Development
Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada. I specialize in React, Node.js & TypeScript application development. If you need help on a project, please reach out, and let’s work together.