Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Use of spread operator when at least one parameter is required

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

like image 380
jacosro Avatar asked Jan 21 '19 10:01

jacosro


People also ask

What is the use of spread operator in typescript?

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.

Can we use spread operator in typescript?

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.

Can you use spread operator on an empty array?

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.

In which cases we use spread operator?

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.


1 Answers

You can create an array type of at least one (or more) items and spread it:

function insert(...elem: [number, ...number[]]) { 
  // ...
}

typings

You could even write a helper type e.g.:

type AtLeastOne<T> = [T, ...T[]]

function insert(...element: AtLeastOne<number>) {
  //...
}
like image 61
jantimon Avatar answered Sep 28 '22 08:09

jantimon