born2net
born2net

Reputation: 24993

Can you explain this odd ES6 arrow function in TypeScript?

using TypeScript:

public subscribe:(subscribeFunction:(state)=>void)=>()=>void;

It's a subscribe method that gets function as an argument, of type function, and that function given, will receive a state argument when called, that argumented function will not return anything (i.e.: void) ... and I am lost on the last ()=>()=>void.

Do I understand this right?

Upvotes: 7

Views: 900

Answers (3)

born2net
born2net

Reputation: 24993

tx for feedback, now that I understand it I think its best explained as:

public subscribe: (subscribeFunction:(state)=>void)

// first potion is for subscribeFunction which will accept a function that does not return anything

=>()=>void;

// second potion is for the subscribe itself as it will return a function that does not return anything... and I agree, code like this should be more explicit

Upvotes: -1

David Sherret
David Sherret

Reputation: 106880

It's for a public property called subscribe that has a type of (subscribeFunction: (state) => void) => () => void;:

// scope
public
// name
subscribe:
// type (function)
    // parameters
    (
        // parameter name
        subscribeFunction:
        // parameter type (function)
        (state) => void
    ) => 
    // return type (function)
    () => void;

Here's an example that compiles:

class MyClass {
    public subscribe: (subscribeFunction: (state) => void) => () => void;
}

let myInstance = new MyClass();

myInstance.subscribe = (subscribeFunction: (state) => void) => {
    console.log("statements might go here");

    return () => {
        subscribeFunction(1 /* state */);
        console.log("nothing returned by this inner function");
    };
};

// Example use

// outputs "statements might go here"
let innerFunction = myInstance.subscribe((state) => console.log(state));
// outputs 1 and "nothing returned by this inner function"
innerFunction();

Upvotes: 8

charlie
charlie

Reputation: 1527

Notice the first colon -- subscribe is a public property of a function type, not a method. Unfolded:

public subscribe: // public property, which is
    ( // of the type of a function, which takes
        subscribeFunction: // 1 parameter, which itself is
        (state) => void // a function of 1 parameter, returning nothing
    ) => // and the upon invocation of a function stored in "subscribe" it
        () => void; // returns a function of no parameter and no return value

Thus, you can store a function into the subscribe property, then call it while giving it a function as a parameter, and as a result you will get another function, which you can subsequently call:

subscribe = (subscribeFunction: (state) => void) => {
    subscribeFunction('A');
    return () => {console.log('C');};
};
let subscribed = subscribe((state) => {
    console.log(state, 'B');
}); // prints 'A,B'
subscribed(); // prints 'C'

Upvotes: 0

Related Questions