Reputation: 3081
I would like to define a function with a rest parameter of either strings or objects, signature like:
public static fn(...messages: string[] | object[]): void;
But unfortunately this results in a TS2370
compile error
error TS2370: A rest parameter must be of an array type.
I know having a single type of array like string[]
or object[]
works fine, but then overloading such function comes with even greater price.
Is there anyway I could make the mentioned function working with the desired signature?
Upvotes: 3
Views: 13211
Reputation: 3199
Yes, you can have multiple types for your rest parameter. However, you must declare it as a single array type:
declare function fn(...messages: (string | object)[]): void;
// or with custom type:
// type MessageType = string | object;
// declare function fn(...messages: MessageType[]): void;
fn('aaa', { });
Otherwise you are saying it can accept an array of strings or an array of objects, however it only accepts 1 typed array
(combining string and object makes it 1 type).
Upvotes: 12