ecmascript 6 - Kan du forklare denne rare ES6 pilfunksjonen i TypeScript?
ved å bruke TypeScript:
public subscribe:(subscribeFunction:(state)=>void)=>()=>void;
Det er en subscribe-metode som får en funksjon som argument, av typen funksjon, og den gitte funksjonen vil motta et state-argument når den kalles, den argumenterte funksjonen vil ikke returnere noe (dvs.: void) ... og jeg har gått meg vill på den siste ()=>()=>void.
Forstår jeg dette riktig?
Svar #1
Det er for en offentlig eiendom kalt subscribe som har typen (subscribeFunction: (state) => void) =>() => void;:
// scope
public
// name
subscribe:
// type (function)
// parameters
(
// parameter name
subscribeFunction:
// parameter type (function)
(state) => void
) =>
// return type (function)
() => void;
Her er et eksempel som kompilerer:
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();
Svar #2
Merk den første kolon -- subscribe er en offentlig egenskap av en funksjonstype, ikke en metode. Utbrettet:
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
Dermed kan du lagre en funksjon i subscribe-egenskapen, deretter kalle den og gi den en funksjon som parameter, og som et resultat vil du få en annen funksjon, som du senere kan kalle:
subscribe = (subscribeFunction: (state) => void) => {
subscribeFunction('A');
return () => {console.log('C');};
};
let subscribed = subscribe((state) => {
console.log(state, 'B');
}); // prints 'A,B'
subscribed(); // prints 'C'
