Say we have a function that accepts a variable number of arguments, I believe it's called variadic function.
Something like this:
function foo(){
let args = Array.from(arguments).map(v => whatever);
// do something with args
}
A TypeScript interface for this function might look like:
interface IVariadicFn {
(...args: string[]): void,
}
but let's say we expect a variable number of strings, but the final parameter, we expect to be a callback function.
So we'd have something like this:
function variadic(){
let args = Array.from(arguments)
let fn = args.pop();
let $args = args.map(v => whatever);
// do something with args
process.nextTick(function(){
fn(null, $args); // fire the callback, asynchronously
});
}
is there a way to declare a TypeScript definition for this function?
The best I can do right now is this:
type IVariadicArgs = string | Function;
export interface IBeforeFn {
(...args: IVariadicArgs[]): void;
}
No, you can't do like you want, but you can pass the first parameter as a function, then the last ones. And also don't use arguments
. You can replace this with rest parameters
interface IVariadicFn {
(func: Function, ...args: string[]): void,
}
function foo(func: Function, ...args: string[]){
let arguments = Array.from(args).map(v => whatever);
// do something with arguments
}
And you can call like
foo(yourFunc, 'asd', 'bsd', 'csd');