I am learning how to use the rest parameter/spread operator in typescript. Now, I need to write a function that takes an array as a parameter and I want to use the rest operator. This is the function:
insert(elem: number, ...elems: number[])
The elem
parameter is there because I need the array to have at least one element.
So, given an array like this:
const numArray = [1, 2, 3, 4]
How can I pass the array to the function? I've tried the following but it gave me an error:
insert(...numArray)
I understand the error, because numArray may have from 0 to N elements, and the function needs at least one element, but I don't know the best solution to it.
Is there any way to achieve this?
Note: The insert
function is part of a library that I'm developing, so I need to make it as usable as can be, and not depending on how the user will make use of it
The spread operator faciliates three common tasks: Copying the elements of one or more arrays into a new array. Copying the properties of one or more objects into a new object.
The spread operator (in form of ellipsis) can be used in two ways: Initializing arrays and objects from another array or object. Object de-structuring.
Array spread At first sight, the difference is only about the brackets. But when it comes to empty values... Unlike object spread, the array spread doesn't work for null and undefined values. It requires anything iterable, like a string, Map or, well, an array.
Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows us the privilege to obtain a list of parameters from an array.
You can create an array type of at least one (or more) items and spread it:
function insert(...elem: [number, ...number[]]) {
// ...
}
You could even write a helper type e.g.:
type AtLeastOne<T> = [T, ...T[]]
function insert(...element: AtLeastOne<number>) {
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With