具有可变参数计数的函数的 TypeScript 类型签名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12739149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript type signatures for functions with variable argument counts
提问by nxn
I'm having trouble defining interfaces with function members that accept variable amounts of arguments. Take the following object literal as an example:
我在定义具有接受可变数量参数的函数成员的接口时遇到问题。以下面的对象字面量为例:
var obj = {
func: () => {
for(var i = 0; i < arguments.length; i++) {
console.log(arguments[i]);
}
}
};
I'd like to be able to define an interface such as:
我希望能够定义一个接口,例如:
interface IExample {
func: ( ??? ) => void;
}
So that the following code can compile without error:
以便以下代码可以编译而不会出错:
var test = (o: IExample) {
o.func("a");
o.func("a", "b");
o.func("a", "b", "c");
...
}
回答by chuckj
TypeScript uses the ECMAScript 6 spread proposal,
TypeScript 使用 ECMAScript 6 传播提案,
but adds type annotations so this would look like,
但是添加了类型注释,所以这看起来像,
interface Example {
func(...args: any[]): void;
}
回答by Serj Sagan
Just to add to chuck's answer, you don't need to have an interface defined as such. You can just do the ...
directly in the method:
只是为了添加到查克的答案中,您不需要定义这样的接口。您可以...
直接在方法中执行:
class Header { constructor(public name: string, public value: string) {} }
getHeaders(...additionalHeaders: Header[]): HttpHeaders {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json')
if (additionalHeaders && additionalHeaders.length)
for (var header of additionalHeaders)
headers.append(header.name, header.value);
return headers;
}
Then you can call it:
然后你可以调用它:
headers: this.getHeaders(new Header('X-Auth-Token', this.getToken()))
Or
或者
headers: this.getHeaders(new Header('X-Auth-Token', this.getToken()), new Header('Something', "Else"))
回答by Quentin 2
If the ...args[] argument is not used Typescript still creates an array in the Javascript and copies the arguments to it.
如果没有使用 ...args[] 参数,Typescript 仍会在 Javascript 中创建一个数组并将参数复制到它。
To avoid this unnecessariness you can make a prototype for the function as well as the function, thus:-
为避免这种不必要的情况,您可以为函数和函数制作原型,因此:-
function format_n(str: string, ... $n: any[]): string;
function format_n(str: string): string {
return str.replace(/%(\d+)/g, (_, n) => format_n.arguments[n]);
}