本文介绍了在 TypeScript 中获取函数参数名称和类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在 TypeScript 中使用了 Parameters 类型,它返回一个带有参数类型的元组.现在我想知道是否有一种方法不仅可以返回参数的类型,还可以返回名称?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?类似于:function MyFunc(a: string, b: boolean, ...args: string[]) {}type extractedType = ParametersWithName<typeof MyFunc>其中 extractedType 结果最终为:{ a: string, b: string}我会用它来将常规函数参数转换为接收参数对象的函数(如 React props).I would use that to convert from regular function parameters to functions that receive a parameter object (like React props).推荐答案无论好坏,参数名称都不是函数类型的一部分.例如,类型签名 (foo: string) =>void 和 (bar: string) =>void 就类型兼容性而言是完全相同的.名称 foo 和 bar(通常)由 IntelliSense 保留作为帮助开发人员的一种文档形式,但它们本质上是实现细节.并且由于不应该有一种方法来区分仅通过参数名称不同的两种函数类型,因此没有提供将这些名称转换为字符串文字类型以用作对象类型的机制.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.在函数参数列表和元组类型之间转换的能力是通过 microsoft/在 TypeScript 3.0 中引入打字稿#24897.这就是使 Parameters 成为可能的原因.该拉取请求对参数名称有以下注释: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).所以绝对没有办法使用 Parameters<> 或类似的东西从函数中提取参数名称并使用它们.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! 这篇关于在 TypeScript 中获取函数参数名称和类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!