3

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?

1 Answer 1

12

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.