简体   繁体   中英

Get function parameter names and types in TypeScript

I've played around with the Parameters<T> type in TypeScript, which returns a tuple with the parameter types. Now I wonder if there's a way to not just return the types of the paramters but also the names?

Something like:

function MyFunc(a: string, b: boolean, ...args: string[]) {}

type extractedType = ParametersWithName<typeof MyFunc>

Where extractedType results ends up as:

{
    a: string, 
    b: string
}

I would use that to convert from regular function parameters to functions that receive a parameter object (like React props).

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).

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

Sorry I don't have a better answer for you. Hope that helps anyway; good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM