0

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;
    }

1
  • The function definition is correct, but you call it as const result = sum(2,4) Commented Jul 30, 2022 at 6:49

3 Answers 3

1

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))

Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

0

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).

3 Comments

@SmallPotato Edited answer to address this.
That works! Thanks a lot! I wasn't come up with a function inside another function.
Thanks for your explanation, I was come up with the whole thing like below at the beginning: const result = sum(2, 4); function sum(x: number, y: number) { return x + y; } console.log('Result:', result); but someone just challenge me if I can rewrite a sum function like sum(2)(4) with the expected same output, then I couldn't come up with your suggested answer lol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.