我正在为一个用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>
}