Search code examples
typescriptsignaturecallable-object

Callable argument has unused name


Is there any reason the parameter name inside a function type exists?

function greeter(fn: (a: string) => void) {
  fn("Hello, World");
}

In the above example (from the docs) why is a needed?


Solution

  • The "Note" in the documentation you linked makes the primary point:

    Note that the parameter name is required. The function type (string) => void means “a function with a parameter named string of type any“!

    Fundamentally, the name is needed because the syntax needs an identifier or similar to apply the type annotation to.¹

    It also has the handy effect of providing a hint your IDE can show you later when you're trying to remember what the argument is. (That's not really important in the example you quoted where the signature is right there, but 20 lines further down, it's handy.)

    But primarily: Because the syntax requires it.


    ¹ Technically, you could have an empty destructuring pattern like ({}: string) => void, but don't do that. :-) It would be misleading to the reader, and problematic if the argument is allowed to be null or undefined (since you can't destructure those).