13

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

2 Answers 2

21

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>) { //... } 
Sign up to request clarification or add additional context in comments.

Comments

2

The problem is that the array is of any length. If you type it as a tuple, with a number element followed by a rest of any number of numbers it will work.

function insert(elem: number, ...elems: number[]) { } const numArray:[number, ...number[]] = [1, 2, 3, 4] insert(...numArray) 

You can also just use a function to help with inference to type the const as a tuple :

function insert(elem: number, ...elems: number[]) { } function tuple<T extends any[]>(...a: T) { return a;} const numArray = tuple(1, 2, 3, 4); insert(...numArray) 

2 Comments

The insert function is part of a library that I'm developing, so I need a solution for the function, and not for the array itself. Sorry for not specifying
@jacosro there is no way to do it without changing the array. If you want to allow arrays, then you can't require that they have at least one element (you ca use insert(...elems: number[]) but that will not require any elements in the array) If you to force at least one element, then the caller need to use a tuple to use the spread syntax.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.