我正在为一个用JavaScript编写的库创建一个typescript声明文件,对于这个任务,我一次又一次地遇到一个问题.所讨论的JavaScript库在许多地方重复了以下模式.

const commandList = [
  "run-like-nuts",
  "some-more-commands",
  "another-nice-command",
  "power-commmand",
  // lots more commands like this
  // in this list 
];


function commandRunner(...args) {
  // Does some internal work based on ...args 
  // returns type Promise<string>
}

commandList.forEach(command => {
  Object.defineProperty(commandRunner, command, {
    value: function(command, ...args) {
      return commandRunner(command, ...args);
    }
  )); 
});

我如何定义commandRunner函数的类型,以便在typescript中使用它时,它是可调用的,并且在commandList中具有属性,从上面的示例中可以明显看出,它也成为可调用的.

到目前为止,鉴于我对typescript的掌握有限,我进行了以下try ,但这并没有解决问题.我如何解决这个问题?

type ArgsType: string | Object;

type commandList = [
  "run-like-nuts",
  "some-more-commands",
  "another-nice-command",
  "power-commmand",
  // lots more commands like this
  // in this list 
];

export default (function commandRunner(...args: ArgsType[]) {}) & {
  [command: Command]: (command: Command,...args: ArgsType[]) => Promise<string>
}

推荐答案

您应该将commandList保留为一个数组,以便我们可以在运行时和编译时使用它.为了使字符串文字可用于键入,我们必须用as const定义它.

const commandList = [
  "run-like-nuts",
  "some-more-commands",
  "another-nice-command",
  "power-commmand",
  // lots more commands like this
  // in this list 
] as const;

对于commandRunner类型,我们可以映射commandList中的字符串文字.

type CommandRunner = ((...args: ArgsType[]) => Promise<string>) & { 
  [Command in typeof commandList[number]]: 
    (command: Command,...args: ArgsType[]) => Promise<string> 
}

Playground

Javascript相关问答推荐

同步功能在中间停止

如何比较嵌套对象的更改并创建更改报告

Express.js:使用Passport.js实现基于角色的身份验证时出现太多重定向问题

React Hooks中useState的同步问题

禁用从vue.js 2中的循环创建的表的最后td的按钮

获取加载失败:获取[.]添加时try 将文档添加到Firerestore,Nuxt 3

微软Edge Select 间隙鼠标退出问题

当在select中 Select 选项时,我必须禁用不匹配的 Select

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

CheckBox作为Vue3中的一个组件

如何从网站www.example.com获取表与Cheerio谷歌应用程序脚本

优化Google Sheet脚本以将下拉菜单和公式添加到多行

Html文件和客户端存储的相关问题,有没有可能?

类构造函数不能在没有用With Router包装的情况下调用

为什么我的getAsFile()方法返回空?

未加载css colored颜色 ,无法将div设置为可见和不可见

将嵌套数组的元素乘以其深度,输出一个和

在查看网页时,如何使HTML中的按钮工作方式类似于鼠标上的滚轮或箭头键?

Clip-Path在网页浏览器(Mozilla、Edge、Chrome)上不能正常工作,但在预览版Visual Code Studio HTML、CSS、JS上却能很好地工作

我怎样才能得到一个数组的名字在另一个数组?