6

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
}
Philipp Meissner
  • 5,273
  • 5
  • 34
  • 59
Hesam
  • 52,260
  • 74
  • 224
  • 365
  • `= (page) => {}` says string (page) goes to this function which returns nothing (void). – Xaqron Sep 02 '17 at 02:10
  • The term "fat arrow function" has been obsolete for several years. They are called simply "arrow functions". –  Sep 02 '17 at 03:52

2 Answers2

13

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Wow that took me a while to see... In my opinion I think that would have been better written as an `interface` for better readability – Get Off My Lawn Sep 02 '17 at 02:13
  • I don't know much about typescript, but I guess it could help if one could wrap the type in parenthesis: `private navigateTo: ((page: string) => void) = (page) => {}` – Felix Kling Sep 02 '17 at 02:14
  • 2
    I take the `interface` part back, It would probably be better written like this: `private navigateTo(page:string): void { }` – Get Off My Lawn Sep 02 '17 at 02:17
5

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.

gretro
  • 1,934
  • 15
  • 25