Use rest parameters to declare a function with variable number of arguments in TypeScript, e.g. function myFunction(... args: string[]) {} . Rest parameters are used when a function takes an indefinite number of arguments. They appear after all other parameters and use the ... syntax.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
Introduction to TypeScript void type The void type denotes the absence of having any type at all. It is a little like the opposite of the any type. Typically, you use the void type as the return type of functions that do not return a value.
TypeScript uses the ECMAScript 6 spread proposal,
http://wiki.ecmascript.org/doku.php?id=harmony:spread
but adds type annotations so this would look like,
interface Example {
func(...args: any[]): void;
}
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With