ecmascript 6 - ¿Puedes explicar esta extraña función de flecha de ES6 en TypeScript?
usando TypeScript:
public subscribe:(subscribeFunction:(state)=>void)=>()=>void;
Es un método de suscripción que recibe una función como argumento, de tipo función, y esa función dada recibirá un argumento de estado cuando se llame, esa función con argumento no retornará nada (es decir: void)... y estoy perdido en el último ()=>()=>void.
¿Lo entiendo bien?
Respuesta #1
Es para una propiedad pública llamada subscribe que tiene un tipo de (subscribeFunction: (state) => void) =>() => void;:
// scope
public
// name
subscribe:
// type (function)
// parameters
(
// parameter name
subscribeFunction:
// parameter type (function)
(state) => void
) =>
// return type (function)
() => void;
Aquí hay un ejemplo que se compila:
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();
Respuesta #2
Observe el primer dos puntos -- subscribe es una propiedad pública de un tipo de función, no un método. Desplegado:
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
Así, puedes almacenar una función en la propiedad subscribe, luego llamarla dándole una función como parámetro, y como resultado obtendrás otra función, que posteriormente puedes llamar:
subscribe = (subscribeFunction: (state) => void) => {
subscribeFunction('A');
return () => {console.log('C');};
};
let subscribed = subscribe((state) => {
console.log(state, 'B');
}); // prints 'A,B'
subscribed(); // prints 'C'
