1

Why do we need to name the parameter types in the type annotation of functions?

let f: (a:number, b:number) => number;

Why is a and b required here?

8
  • 1
    It's a design decision on the TS designers part. They are there for semantic documentation. Commented Aug 27, 2020 at 8:42
  • 2
    Becsuse a good variable naming is a key to an efficient and readable code. Without argument names you will have to provide an annotation for every parameter. Parameters like a and b make no sense for another developer, while haystack and needle are self-descriptive Commented Aug 27, 2020 at 8:43
  • 2
    Which one do you find more clear (string, string, number) => Person or (firstName: string, lastName: string, age: number) => Person? Commented Aug 27, 2020 at 8:49
  • Although I agree with those who say it is clearer to require names, it is worth pointing out that there would be a syntactic ambiguity if names were optional. Commented Aug 27, 2020 at 14:30
  • @AluanHaddad why is that? Commented Aug 27, 2020 at 18:11

1 Answer 1

2

This is a design decision to make the code more readable. Also parameters in "normal" functions also need a name. Let's take the example of you using a libary which includes arrow functions, what do you think is easier to use of the following two examples?

const getResult: (string, number?, number?) => queryObject;

or

const getResult: (id: string, startIndex?: number, endIndex?: number) => queryObject;

I hope this makes it clear to you

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

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.