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.
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!
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.
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.
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).
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