Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript, define a type for an array where the first element is more specific than the rest

I would like to define a type for an array whose first element is a specific type (e.g. Function), and the remaining elements are the empty type. For example:

type FAs = [Function, {}, {}, {}, ...]; // pseudo code 

Is such a thing possible?

The purpose is to provide a single-argument function like this:

const myCaller = ([fun, ...args]: FAs) => fun.apply(args); 

An alternative approach would be to use two arguments to myCaller, like this:

const myCaller = (fun: Function, args: any[]) => fun.apply(args); 

but for aesthetic reasons I would prefer to use a single argument. I also wonder if the type system supports what is arguably an arbitrary-length tuple. Maybe such a thing is undesirable for computer science reasons I don't understand.

like image 975
anticrisis Avatar asked Jun 07 '17 01:06

anticrisis


People also ask

How do you define a type of array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you select the first element of an array?

There are several methods to get the first element of an array in PHP. Some of the methods are using foreach loop, reset function, array_slice function, array_values, array_reverse, and many more. We will discuss the different ways to access the first element of an array sequentially.

How do you push an element in an array at first position in TypeScript?

Adding new elements at the beginning of existing array can be done by using Array unshift() method. This method is similar to push() method but it adds element at the beginning of the array.


1 Answers

In current versions of Typescript this is possible using array spread:

type FAs = [Function, ...Array<{}>]

It supports any length from 1 to n (the first element is required).

like image 50
juusaw Avatar answered Sep 19 '22 11:09

juusaw