Exploring TypeScript: Strategies for typing multi-dimensional arrays with varying shapes

How can I design an interface for a two-dimensional array that may vary in shape and contain either numbers or strings?

For instance:

// scenario one
[[0]]

// scenario two
[
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// scenario three
[
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]

Answer №1

If you're looking for a generic type to use with 2D arrays, you can implement it like this:

// Defining a generic 2D array type
type Arr2DGeneric<T> = T[][];
// The key is to interpret this type from right to left: An array ([]) of arrays ([]) of type T

// Example one
const g1: Arr2DGeneric<number|string> = [[0]]

// Example two
const g2: Arr2DGeneric<number|string> = [
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// Example three
const g3: Arr2DGeneric<number|string> = [
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]

Alternatively, as suggested by @Nalin Ranjan, you can define the specific type for your example like this:

// Specific type for number | string
type NumStrArr2D = (number|string)[][];


// Example one
const ns1:NumStrArr2D = [[0]]

// Example two
const ns2:NumStrArr2D = [
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
  [0, 'I', 0, 0],
]

// Example three
const ns3:NumStrArr2D = [
  [0,   'J', 0],
  [0,   'J', 0],
  ['J', 'J', 0],
]

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

Encountering an error when trying to declare a type in VSCode with ESlint and React Types

After setting up an axios configuration file with proper typing support, I encountered the following error message: import axios, { AxiosRequestConfig, AxiosInstance } from 'axios'; const api = axios.create({ baseURL: '/api', resp ...

Issue with recognizing baseUrl and paths in tsconfig.json in Visual Studio 2017 for Typescript files

Currently, I am utilizing Visual Studio 2017 ASP.NET Core with Angular. However, I am facing an issue where Visual Studio does not seem to recognize the shortcuts when I attempt to set baseUrl/paths. I am unsure if this is a result of misconfiguration on ...

Issue with MUI Select custom MenuItem functionality not functioning as expected

Having an issue with MUI's MenuItem in conjunction with Select and rendering it within a separate component. Check out the codesandbox for reference. The setup is as follows: import { Select } from "@material-ui/core"; import CustomMenuIte ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

Angular is declining to implement the style originating from the specified URL

I'm currently working on an Angular application and attempting to lazy load a module called ProjectsModule. The projects component is displayed without any issues, but when I navigate to a specific project like /projects/1, everything looks fine until ...

Understanding how to infer the type of a function when it is passed as an argument

Looking at the images below, I am facing an issue with my function that accepts options in the form of an object where one of the arguments is a transform function. The problem is that while the type of the response argument is correctly inferred for the e ...

Unable to connect to 'highlight' as it is not a recognized attribute of 'code'

I have been experimenting with ngx-highlightjs and encountered an issue while trying to implement it in one of my module files. Due to having multiple modules, I am importing the HighlightModule only in the specific module where highlighting functionality ...

Learn the art of bypassing TypeScript errors using @ts-ignore!

I recently encountered an issue when trying to import a pure JavaScript library into a TypeScript project, resulting in the error message: Could not find a declaration file for module xxx. After some research, I learned that this error can be suppressed u ...

TypeScript compiler not processing recently generated files

While working on a project using TypeScript, I've noticed that the files compile without any issues when using tsc with the watch flag to monitor changes. However, I have run into an issue where when I create a new file, tsc does not automatically det ...

Strategies for managing the "ref" property of Material-UI component props within our custom components

I have a unique custom component setup as shown below: // ... import { PaperProps, styled } from '@mui/material'; type ComponentProps = PaperProps & { a: string, b: string }; export const MyPaper = styled(Paper)(/* ... */); const Compo ...

Challenges encountered when executing a node function in an AWS Lambda function

I have observed some unusual behavior with my AWS Lambda function. Here is the code snippet for the Lambda: import { TwitterApi } from 'twitter-api-v2'; const client = new TwitterApi({ appKey: 'APP_KEY', appSecret: 'APP_ ...

Creating an array that exclusively contains numbers using anonymous object export: A step-by-step guide

I am struggling with a record that is designed to only accept values of type number[] or numbers. This is how it is structured: type numberRecords = Record<string,number[]|number>; I ran into an error when trying this: export const myList:numberRec ...

Determining whether a Typescript AST node represents a javascript native function

How can I determine if an AST node in TypeScript represents a valid JavaScript function, as opposed to a custom method? Here's what I'm thinking: function isJavascriptFunction(node: ts.Node): boolean { // ----- } For instance, given the cod ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

Error: Angular encountered an unexpected token in the syntax

I am encountering an issue while trying to incorporate a user's profile updater on my website. Whenever I attempt to access a user's profile on the site, I run into this Angular error: main.ts:6 ERROR SyntaxError: Unexpected token 'e', ...

Creating a Vue 3 Typescript project may lead to encountering the error message "this is undefined"

Just diving into Vue using Vite and TypeScript for my project, but running into errors during the build process. Most of them are Object is possibly 'undefined', particularly in parts of my template like this: <input :value="this.$store.s ...

Is it possible to apply async/await within a describe block?

I have been struggling to run the following complete end-to-end test for my project. I have a collection of pages, each consisting of a page title and a list of steps required. However, in order to retrieve these pages, an asynchronous call is necessary. C ...

List of suggestions for autocomplete in Angular

My autocomplete function is set up like this: chooseArtist: OperatorFunction<string, readonly string[]> = (text$: Observable<string>) => text$.pipe( debounceTime(200), distinctUntilChanged(), map((term: any) => term. ...

Can the return value of a function be directly used as the variable type?

Imagine having the following function: let getData = () => { return { name: 'John', age: 2, isAsian: true } } Is there a way to specify a variable's type as the return type of getData, without assigning i ...