typescript - 打字稿只复制函数参数而不是返回类型
问题描述
我有一些实用方法,我想知道是否有办法将参数从一种方法复制到另一种方法。我正在玩弄typeof
并尝试以这种方式输入第二个函数,但我无法弄清楚。
declare function foo(a: number, b: string): number;
现在我想要一个类型bar
有foo
参数,但没有返回类型,例如,假设它调用 foo 但不返回任何内容:
const bar = (...args) => { foo(...args); }
现在我可以声明bar
具有与以下完全相同的类型foo
:
const bar: typeof foo = (...args) => { foo(...args); }
但返回类型现在不匹配。那么我该怎么做:
- 只需复制参数签名
- 更改我从中获得的返回类型
typeof foo
解决方案
有内置的参数类型
declare function foo(a: number, b: string): number;
type fooParameters = Parameters<typeof foo>;
declare const bar: (...parameters: fooParameters) => void;
// inferred as const bar: (a: number, b: string) => void
推荐阅读
- php - 为什么“if(!session_id() Then Do This”条件在 Session ID 已经存在时触发?
- php - div 元素不在现场渲染,但显示在检查器中
- django - 将 Django 部署到 Elastic Beanstalk,迁移失败
- powershell - 在 PowerShell 中转换为自定义类
- python - 机器人框架 - 无效的 xpath 表达式
- python - Python 函数卡在 for 循环中
- java - 什么时候在 React Native 应用程序(使用 Expo)中编译原生模块?
- javascript - 使用 Google Drive API 将 CSV 文件上传到用户的驱动器,无需后端
- java - 为什么我在尝试发送 http 请求时收到 SSLProtocolExcepetion: Handshake failed ?
- javascript - 如何按如下定义的顺序创建数组?