How can I create a one line function in typescript return like this:
sum(x)(y) -> x y, e.g sums(2)(4) -> 6
Given that:
const result = sum(2)(4); // 6
console.log('Result:', result);
I have tried with a way like this:
function sum(x: number, y: number) {
return x y;
}
CodePudding user response:
function sum(x){
return function(y){
return x y;
};
}
const result = sum(2)(4); // 6
console.log('Result:', result);
With ES6 arrow functions;
let sum = (x) => (y) => x y;
console.log('Result:', sum(2)(4)); // 6
CodePudding user response:
Like this
const sum = (x: number, y: number): number => x y;
console.log("sum", sum(1,2))
const sumNested = (x: number) => (y: number): number => x y;
console.log("sumNested", sumNested(3)(4))
CodePudding user response:
You must separate your arguments with commas, not parentheses, like so:
const result = sum(2, 4);
If you really want to use sum(2)(4)
:
function sum(numOne) {
return function(numTwo) {
return numOne numTwo;
}
}
sum(2)(4) // 6
This occurs because the sum
function returns another function, and the second pair of parentheses (the (4)
part), executes another function.
This is generally bad practice though, so you are better off using sum(2, 4)
.