0
export const a= {
    b:
    (): c => (d, e) => {
         return d+e
       }

I am having trouble understanding what the code above does. I am confused by the usage of (): what exactly is the b function if it is translated into plain javascript? If I call a.b(), what actually happens?

2 Answers 2

2

The best way to find solutions to stuff like this is using the typescript online compiler. If you look here: http://www.typescriptlang.org/play/#code/C4TwDgpgBAxlC8UCGA7EBuAUJiAPMA9gE7CwEoDOpSCUA3plFAEYBcjTUAFAJSuwIAfNwAmAGigQeQ+h05QiEYAFciKKCKgBqSXKgBfTPqA

You can see that the function b returns the function:

(d, e) => {
    return d+e
}

and this function is of type c.

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

3 Comments

does the return type of 'd+e' have to be same as defined in c?
c is going to be type (d: any, e:any)=>any
i guess i am still a bit confused, if c has 2 parameters d and e, and b is of type c, why b does not have any parameter while we still call it as a.b() rather than a.b(d,e)?
1

what exactly is the b function if it is translated into plain javascript?

export const aJS = {
  b: () => (d, e) => d + e
}

aJS.b()(3,4) // 7

So aJS.b is some kind of thunk or deferred function call.


In the TS version, c is a type. You can (1) leave out c and let the compiler infer the function type or (2) create a contextual function type and have the function arguments be inferred (code sample):

(1)

const a = {
  b: () => (d: number, e: number) => d + e
}

a.b()(3, 4) // 7

(2)

type c = (n1: number, n2: number) => number

const a2 = {
  b: (): c => (d, e) => d + e
}

a2.b()(3, 4) // 7

Comments

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.