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
}
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.
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.
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 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) {...} .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With