Nan Li
Nan Li

Reputation: 593

How to type the union of a single parameter and rest parameters with typescript?

if I have a function that takes either an object or a list of items as parameters,

f1 = (p: Object) => ...
f1 = (...p: string[]) => ...

this is what I want to achieve, but apparently it doesn't work:

f1 = (p: Object | ...p: string[]) => ...

how do I type this kind of 'union'?

Upvotes: 1

Views: 128

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You can use overloads for function declarations or tuples in rest parameters:

const f1 = (...p: [object] | string[]) => { }
f1({})
f1({}, {}) //err
f1("")
f1("", '')

Upvotes: 3

Related Questions