Get function parameter names and types in TypeScript

For better or worse, parameter names are not part of a function’s type. For example, the type signatures (foo: string) => void and (bar: string) => void are completely identical as far as type compatibility is concerned. The names foo and bar are (usually) preserved by IntelliSense as a form of documentation to help developers, but they are essentially implementation details. And since there isn’t supposed to be a way to distinguish two function types that differ only by parameter names, there’s no mechanism provided to convert these names into string literal types for use as object types.

The ability to convert between function parameter lists and tuple types was introduced in TypeScript 3.0 via microsoft/TypeScript#24897. This is what makes Parameters<> possible. That pull request has the following remark about parameter names:

Note that when a tuple type is inferred from a sequence of parameters and later expanded into a parameter list, … the original parameter names are used in the expansion (however, the names have no semantic meaning and are not otherwise observable).

Labeled tuple elements introduced in TypeScript 4.0 allow you to convert between parameter names and tuple labels, but neither of these are observable to the type system as string literal types.

So there’s definitely no way to use Parameters<> or something like it to pull parameter names out of a function and use them.

Leave a Comment