Ensure that the 2D array of tuples in Typescript contains at least one element

In my Typescript variable declaration, I implemented a type check to ensure that all elements in an array of tuples are of length 2 and consist of numbers:

const testArea: [number, number][] = [[0, 0], [0, 220000], [220000, 220000], [220000, 0]];

This approach successfully initializes the variable, but it still permits an empty array:

const testArea: [number, number][] = []; // No error

I attempted to modify this as follows:

const testArea: [[number, number]] = [[0, 0], [0, 220000], [220000, 220000], [220000, 0]]; // error: only allows a single tuple in the array

However, this did not work for cases where there are multiple tuples in the array (although it does prevent an empty array from being valid).

Is there a way to verify that the outer array contains tuples of type [number, number] and also ensure that it contains at least one of these tuples?

Answer №1

A simple trick using the rest operator can solve this issue.

type Tuple = [number, number]

type NonEmptyArray<T> = [T, ...T[]];

type Data = NonEmptyArray<Tuple>

const data: Data = [] // error
const data1: Data = [[]] // error
const data2: Data = [[1]] // error
const data2: Data = [[1,1]] // Ok

Various alternatives exist to ensure that the array is not empty,

one of which is:

type NonEmptyArray2<T extends unknown[]> = T['length'] extends 0 ? never : T

For more information, you can refer to @jcalz's answer here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for converting a two-column matrix into a structure resembling a multimap?

Is there a way to convert a matrix with 2 columns into a multimap or list of lists? The matrix's first column contains IDs (which may be duplicated) and the second column contains values. For instance, consider the following matrix: m <- matrix( ...

Different method for creating arrays in Header file without the use of C++11

In my header file, I have created a class that initializes and fills three arrays as shown below: class SampleClass { private: string array1[5] = {"sample1", "sample2", "sample3", "sample4", "sample5"}; double array2[4] = {20.7, 26.4, 27.8, 31.1}; ...

kotlin: issues arise with arrays when using annotations

I'm facing an issue with annotations on my Entity Table: Entity Table(uniqueConstraints = array(UniqueConstraint(columnNames = array("key", "userid")))) public class ... This is resulting in the following error message: Type inference failed. Ex ...

Combining two arrays using a delimiter for rows in JQuery

I have two arrays containing selectedGuids and selectedUserNames values. selectedGuids = $('.chkAllDates:checked').map(function () { return $(this).attr('Guid'); }) ...

Encountering an issue while trying to import the instanceMethods function within Sequelize

In a file, I have written a function and exported it like this: export function foo(params...) { // do something } When initializing the model, I imported the function in the following manner: import { foo } from "../path/..." instanceMethods: { foo ...

Creating a multiline array in Pascal: A step-by-step guide

Is it possible to create an array per line without including double quotes and commas? I have created a basic array as shown below. var Month: array [1 .. 5] of string = ('January', 'February', 'March', 'April', ...

Output JSON in PHP with key-value pair

Why is this code not functioning as expected? What mistake have I made? $json = json_encode($myInstance->getData($id)); $result = json_decode($json,true); $i = 0; foreach ($result as $value) { echo '<div>'.$value[$i] ...

What is the best way to add a constant value to all objects within an array without having to iterate through each one

Is there a more concise way to add a fixed value to each object in an array without using a loop in JavaScript? Programming Language used: JavaScript Example Array: "cars": [ { "name":"Ford", "models":"Fiesta" }, { "name":"BMW", "models":"X1" }, ...

My superscript character keeps getting escaped in the Angular component HTML

I am encountering an issue with displaying a squared character in my Angular 5 component. Area Breakdown m² When rendered, the squared character is being displayed incorrectly as: Area Breakdown m&sup2; component.ts @Component({ templateU ...

First, download a npm package and integrate it into TSX files

Hello all, I am currently working on my very first project using React, Typescript, and ASP.NET Core. As a beginner in this technology stack, I seek your patience and understanding as I encounter challenges along the way. Right now, I'm facing an issu ...

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

What is the most effective method for importing four data files and organizing them into an array of structures using functions?

To begin, I am tasked with importing data from four separate input files. Next, I need to organize this data into an array of structures and perform some data manipulation. Finally, the manipulated data must be outputted to a new file. I have never dealt ...

Getting the local path of a file from an input file in Angular 7

Is there a way to retrieve the local file path from an input field in HTML? After running the code below, I obtained 'C:\fakepath\fileTest.txt' I am looking for a method to get the local path so that I can pass it on to my control ...

What steps can be taken to delete a database entry if the saved object is not included in the updated client request?

Suppose you have a database entry created with two objects from an array in the request payload. Request : {"users":[{"identifier":"abctest","name":"uan"},{"identifier":"deftest","name":"Aj"}]} Response : {"users":[{"id":182,"identifier":"abctest","name" ...

How can we utilize the strcpy function to duplicate a string array into another string or a distinct array?

Hey there! I'm still fairly new to C++, and just completed an assignment that involved creating a menu with 7 different options. I was able to finish all the tasks except for option 7, which required me to copy an array to another array and output th ...

trouble encountered when trying to form an array with attributes sourced from a different class (using typescript)

Having trouble creating an array of objects from one class in another class. When I try to push them, an error occurs saying "Cannot read property '0' of undefined." Any help would be greatly appreciated. Here is an example using typescript: exp ...

retrieving data from a tuple that corresponds to a dictionary entry

I'm currently utilizing networkx and in need of sorting the edges based on the weight values. The edges are represented as a list of tuples with the weight stored within a dictionary as the third element of the tuple: G.edges = [(u, v, {'weight&a ...

What is the best way to incorporate dynamic infographics into an ionic app?

Looking to design unique infographics for my ionic app, similar to the ones seen here: Any recommendations on tools or strategies for creating these infographics? ...

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

ESLint is reporting an error of "Module path resolution failed" in a project that includes shared modules

Encountering ESLint errors when importing modules from a shared project is causing some frustration. The issue arises with every import from the shared/ project, presenting the common ESLint import error: Unable to resolve path to module 'shared/hook ...