How to add types to `...args` in typescript

Viewed 11677

I have a function like this

function foobar(...args): any {
    ....
}

The function signature is rather general, but it only accepts strings and an last an object of type X (all being optional)

foobar();
foobar('a');
foobar('a', 'b', 'c');
foobar('a', { ... });
foonbar('a', 'b', { ... }); 

Is there some way that types can be added, for example

function foobar(...args: [...string, X]) {  // this doesn't work!

}

Any suggestions ?

2 Answers

You can set any type you want for the ...args spread argument but it has to be an array of something

i.e.

function foobar(...args: string[]): any {
    ....
}

In your case there is no way to specify a certain type for the last object but you could do something like

function foobar(...args: Array<string | IYourCustomType>): any {
    ....
}

In general it is common practice to put the fixed arguments first and the optional arguments last so I would rewrite the function as

function foobar(obj: IYourCustomType, ...args: string[]): any {
    ....
}
Related