具有可变数量/参数类型的函数的TypeScript声明文件 [英] TypeScript declaration file for function with variable number/type of arguments
问题描述
headjs在其API上做了一些非常疯狂的JavaScript类型的事情。例如,它为函数接受任意数量的字符串(不是字符串数组)。有时它会结束相同的函数调用,例如,你可以选择以函数结束它。
headjs does some very crazy JavaScript type things to its API. For instance it takes an arbitrary number of strings (not a string array) for a function. Sometimes it ends that same function call, you can optionally end it with a function, for example.
head.js("scripturl1", "scripturl2",...,callback);
您也可以(同样容易)执行以下操作
You can also (just as easily) do the following
head.js({scriptlabel:"scripturl1"},{scriptlabel2:"scripturl2"},...., callback);
我的问题是我们如何在声明文件中描述HECK?由于我当前的传递似乎完全错误,所以我全都听到了。
My question is how the HECK do we describe that in a declaration file? I am all ears here as my current pass seems completely wrong.
推荐答案
TS语言规范将变量数/传播参数称为休息参数。具有接受休息参数的函数签名的示例接口:
The TS language spec refers to variable number/spread parameters as "Rest Parameters". An example interface with a function signature that accepts rest params:
interface IExample {
fn : (...args : any[]) => any;
}
var x : IExample = {
fn: function(...args : any[]) {
for (var i = 0, arg; arg = args[i]; i++) {
console.log(arg);
}
}
}
x.fn(1);
x.fn(1, 2);
x.fn("cat", "dog", "mouse");
不幸的是,存在一些限制。 Rest Parameter必须是函数签名中的最后一个 - 因此您将无法捕获回调参数的类型,因为它位于重复参数之后。
Unfortunately, there are some limitations. The "Rest Parameter" has to be the last one in a function's signature -- so you won't be able to capture the type of the callback parameter since it is after the repeating parameter.
如果不是,你可以这样做:
If it wasn't, you would have been able to do something like this:
var fn = function(cb: Function, ...args : string[]) {
...
}
这篇关于具有可变数量/参数类型的函数的TypeScript声明文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!