Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array to variadic function in TypeScript

Tags:

typescript

I have a method that should accept either an array of numbers or accept a variable number of number arguments (variadic). In most languages I've used, when you make a method/function variadic, it accepts both, but it seems that in TypeScript, you cannot. When I make this particular function variadic, all of the places where I supply a number[] fail compilation.

Signature for reference (in class ObjectIdentifier):

constructor(... nodes : number[]) {

This fails:

return new ObjectIdentifier(numbers);

where numbers is of type number[].

like image 828
Jonathan Wilbur Avatar asked Mar 06 '26 01:03

Jonathan Wilbur


1 Answers

Use the following syntax:

const func = (...a: number[]) => console.info('a', a)

func(1, 2, 3)

func(...[1, 2, 3])
like image 136
kemsky Avatar answered Mar 08 '26 19:03

kemsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!