是否有 ArgumentsType<T>像 ReturnType<T>在打字稿? [英] Is there ArgumentsType<T> like ReturnType<T> in Typescript?

查看:18
本文介绍了是否有 ArgumentsType<T>像 ReturnType<T>在打字稿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReturnType 提取函数的返回类型.

ReturnType<T> extracts return type of a function.

有没有办法定义ArgumentsType,以tuple格式提取函数的参数类型?

Is there a way to define ArgumentsType<T> that extracts parameter types of a function in tuple format?

例如

ArgumentsType<(a: number, b: string) =>boolean> 将是 [number, string].

推荐答案

编辑

自从编写原始答案以来,typescript 现在有一个内置类型(在 lib.d.ts 中定义)来获取名为 Parameters

Since writing the original answer, typescript now has a built-in type (defined in lib.d.ts) to get the type of the parameters called Parameters

type argsEmpty = Parameters<() => void> // []
type args = Parameters<(x: number, y: string, z: boolean) => void> // [number, string, boolean]
type argsOpt = Parameters<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]

编辑 Typescript 3.0 已发布,以下代码按预期工作.

Edit Typescript 3.0 has been relesed the code below works as expected.

虽然在当前版本的 typescript (2.9) 中,如果没有拼出所有参数,这是不可能的.这将在未来几天发布的下一个 typescript (3.0) 版本中成为可能:

While this is not possible in the current version of typescript (2.9) without spelling out all parameters. It will become possible in the next version of typescript (3.0) which will be released in the next few days:

type ArgumentsType<T> = T extends  (...args: infer U) => any ? U: never;

type argsEmpty = ArgumentsType<() => void> // []
type args = ArgumentsType<(x: number, y: string, z: boolean) => void> // [number, string, boolean]
type argsOpt = ArgumentsType<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?]

如果你安装了 npm install typescript@next 你已经可以玩这个了,它应该在本月的某个时候可用.

If you install npm install typescript@next you can already play with this, it should be available sometime this month.

注意

我们还可以使用这个新功能将元组传播到参数中:

We can also spread a tuple into arguments with this new feature:

type Spread<T extends any[]> = (...args: T)=> void;
type Func = Spread<args> //(x: number, y: string, z: boolean) => void

您可以在此处

这篇关于是否有 ArgumentsType&lt;T&gt;像 ReturnType&lt;T&gt;在打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆