Small Potato
Small Potato

Reputation: 7

Writing a sum function in Typescript?

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

Upvotes: 0

Views: 872

Answers (3)

Maytha8
Maytha8

Reputation: 866

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

Upvotes: 0

Irfanullah Jan
Irfanullah Jan

Reputation: 3892

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

Upvotes: 1

Bishan
Bishan

Reputation: 15710

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

Upvotes: 1

Related Questions