Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of "void = () => {}" after Fat arrow function in TypeScript?

I saw this block of code in our code base and I have a bit of a problem to understand void = (page). According to https://stackoverflow.com/a/34274584/513413, the return type is coming after => which is void in my case. So what does = (page) => {} do? What is its equivalent function if I don't write it with fat arrow function?

This is the code:

private navigateTo: (page: string) => void = (page) => {
    // display page
}
like image 292
Hesam Avatar asked Sep 02 '17 02:09

Hesam


People also ask

What does () => void mean TypeScript?

The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any . Note that the parameter name is required.

What is the meaning of => in TypeScript?

ES6 version of TypeScript provides an arrow function which is the shorthand syntax for defining the anonymous function, i.e., for function expressions. It omits the function keyword. We can call it fat arrow (because -> is a thin arrow and => is a "fat" arrow). It is also called a Lambda function.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.

What does => mean in code?

What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .


2 Answers

You are looking at the code incorrectly. The general structure is

private Name: Type = Value

The type is (page: string) => void and the value is (page) => {}. The type means that navigateTo is a function that accepts a string as argument and returns nothing, which is what (page) => {} does.

like image 168
Felix Kling Avatar answered Sep 23 '22 19:09

Felix Kling


In Typescript, typings are inserted inside the statements of the language, transforming them a bit.

The code you submitted should read as such:

  • private navigateTo: This part is straighforward. We create a private member called navigateTo inside the current class.
  • ...: (page: string) => void: This is the type of the member. In this case, it represents a function taking in a string parameter and not returning anything (void). This part is purely Typescript.
  • ... = (page) => { /* display page */ }: This is the actual function being assigned to the variable.

I recommend you read some of the Typescript Handbook. It has a lot of information about the syntax and the language.

like image 30
gretro Avatar answered Sep 23 '22 19:09

gretro