0

I am looking at a piece of code in a react application:

export const clickOptOutMessage = (): ClickOptOutMessage => ({
  type: CLICK_OPT_OUT_MESSAGE,
});

What does the (): do? I am having trouble googling this due to the fact that it's just a bunch of characters.

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
snowflakekiller
  • 3,428
  • 6
  • 27
  • 45
  • 3
    You are missing typescript tag. Also to answer your question, its called [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions). `: ClickOptOutMessage` is a part of typescript, which means function will return value of type `ClickOptOutMessage` – Rajesh Aug 18 '17 at 05:48
  • Not sure if this is an exact dupe, but this will help: https://stackoverflow.com/questions/34274520/whats-the-meaning-of-in-typescript-fat-arrow – Rajesh Aug 18 '17 at 05:52

1 Answers1

2

I'll try to explain step by step (sorry if you already know everything except ending, some people may learn something new)

() => { /** function body goes here **/ }

is an arrow function

() => {} 
//basically equals:
(function () {}).bind(this)

It will always have context where it was written.

In TypeScript you can write function return type, like this:

function(): number {
  return 2;
}

So, now you know that since arrow function is just another function with slightly different syntax - (): TYPE is just a return type!

export const clickOptOutMessage = (): ClickOptOutMessage => ({
  type: CLICK_OPT_OUT_MESSAGE,
});

Somewhere in the code you looked at, there is this piece:

const CLICK_OPT_OUT_MESSAGE = "CLICK_OPT_OUT_MESSAGE"; // value can differ in code you observed

type ClickOptOutMessage = {
  type: "CLICK_OPT_OUT_MESSAGE"
}

As you can see,

(): ClickOptOutMessage

pretty much tells the type of return value.

idchlife
  • 554
  • 1
  • 6
  • 16