1

I am trying to learn TypeScript using Barasat Ali Syed's Deep Dive.

I came across below code in Arrow Functions and inheritance. Please help me understand what is the significance of second :string in this line "(b:string) : string"

class Adder {
    constructor(public a: number) {}
    // This function is now safe to pass around
    add = (b: string): string => {
        return this.a + b;
    }
}
6
  • It's a return type of an anonymous function. Commented Apr 6, 2017 at 2:12
  • @zerkms : Is it because of TypeScript, that we have to specify return type and is it compulsory? I do not remember specifying return type in javascript. Commented Apr 6, 2017 at 2:37
  • JS is completely untyped. And in TS typing is optional. Commented Apr 6, 2017 at 2:42
  • @zerkms : Would it be completely normal if I use (b: string) instead of (b: string): string ? Commented Apr 6, 2017 at 2:44
  • TS would infer the type automatically from your code in such case then. In this case it would see that you return number + string that is of a type string. Commented Apr 6, 2017 at 2:46

1 Answer 1

1
(b: string): string => { ... }

Is an anonymous arrow function. The second :string is a definition of the return type of this function.

On your Adder class, you are defining a property add and assigning an anonymous function that expect a string argument b parameter and return a string value.

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

1 Comment

Thanks for your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.