Using an anonymous array in Typescript as a parameter for a function

I encountered an issue with Typescript 4.9 that I'm struggling to resolve. While I grasp the reason behind the error, I am unsure of how to work around it. I attempted nullish coalescing, but it led to more errors. The parameter will consistently be a two-dimensional array containing one or more sets of data.

private CreatePlots(data: []) {
    let valData = data[0][0];
    let plotInfo = <EpmsPlotQueryData>data[0][1];
    GUI.setPopupMsg("Loading query data " + this._processResults + " of " + this._PlotQueryList.length);
    plotInfo.createPlots(valData);
}

The error is arising in both references to data; https://i.sstatic.net/gREyG.png

https://i.sstatic.net/5r3NR.png

To bypass these errors, I could modify the function to have data defined as any, like so:

private CreatePlots(data)

However, I'm curious as to why I can't use an empty array as in JavaScript.

Answer №1

When specifying the exact type of a parameter, declare it as shown below:

data: Array<[string, EpmsPlotQueryData]>
or
data: [string, EpmsPlotQueryData][]
(both are equivalent), representing an array of tuples.

private CreatePlots(data: Array<[string, EpmsPlotQueryData]>) {
    let valData = data[0][0];
    let plotInfo = data[0][1];
    GUI.setPopupMsg("Loading query data " + this._processResults + " of " + this._PlotQueryList.length);
    plotInfo.createPlots(valData);
}

The error you're encountering can be explained by:

  • data: any[] denotes an array of any type
  • data: [number, string] indicates a tuple where data[0] is a number, data[1] is a string, and there is no data[2]
  • data: [] signifies an empty tuple, suggesting that an empty tuple will always be returned (an array that is perpetually empty).

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

The outcome from using Array.reduce may not always match the expected result

After discovering an unexpected behavior in Typescript's type-inference, I suspect there may be a bug. Imagine having a list of the MyItem interface. interface MyItem { id?: string; value: string; } const myItemList: MyItem[] = []; It's ...

Typescript: Dynamically assigning array type based on preceding array element

Can Typescript support the implementation of an infinite Array (not a Tuple) with a type that depends on the previous element of the array? Here is a sample pseudo-typescript code: class B<T, U> {} function foo<X, Y>(...args: [B<X, Z0>, ...

Tips on using the map and filter methods to narrow down a nested array based on specific object

I am struggling to filter JSON data based on a specific date using Array.Filter and Map. The code I have tried below is not yielding the desired results. Can someone please provide guidance on how to effectively filter JSON data based on a particular date ...

Angular routing is failing to redirect properly

After creating a sample Angular app, the goal is to be redirected to another page using the browser URL http://localhost:1800/demo. The index.html file looks like this: <!doctype html> <html lang="en"> <head> <title>Sample Ang ...

Angular 2 - retrieve the most recent 5 entries from the database

Is there a way to retrieve the last 5 records from a database? logs.component.html <table class="table table-striped table-bordered"> <thead> <tr> <th>Date</th> <th>Logging ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } expor ...

PreventDefault was ineffective in handling close/minimize/maximize BrowserWindow events in electron

I need help with customizing the behavior of the close, minimize and maximize events in the Electron browser window. I have been able to capture these events, but using event.preventDefault() does not seem to work as expected. Rather than disabling the win ...

Is it possible for Typescript to utilize Webpack's UMD feature for importing

Is there a method in TypeScript to import a module wrapped by webpack UMD (Universal Module Definition)? For instance: npm install knockback The file .js (node_modules/knockback/knockback.js) starts like this: (function webpackUniversalModuleDefinition( ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Looking to organize an array of objects containing two string elements (countries) based on the country name using TypeScript or the Lodash library?

Below is an example of an array of objects I am working with: { countries: [{ "country_alpha2_code": "PW", "country_name": "PALAU" },{ "country_alpha2_code": "US&qu ...

declare wrong TypeScript type in external library

I am currently using winston 3.0 in combination with the @types/winston types. Unfortunately, it seems that these types are not completely compatible, leading to an error in the types that I am unsure how to rectify. Below is the code snippet in question: ...

Bring in a template in TypeScript with no need for require statement

Currently, I'm utilizing TypeScript along with Angular 1.5 component. In my scenario, I have a custom decorator in place through which I send templates via require function. The setup is functional; however, I am consistently receiving a tslint warnin ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

"Define a TypeScript function type that can return either an object or a string depending on whether it succeeds or fails

I encountered an issue with a function that either returns a Promise on success or a string on error. async create(createDebtorDto: CreateDebtorDto): Promise<Debtor> { console.log("createDebtorDto", createDebtorDto) try{ const createdD ...

Angular: Issue with the functionality of BehaviorSubject

Seeking assistance in retrieving the current value of a BehaviorSubject in Angular. I utilized these lines to print and check its content on the console: console.log(this._isNumeric) console.log(this._isNumeric.getValue()) However, the output shows: close ...

`Are you incorporating Material UI tabs with React Router in your project?`

Looking for help with a project utilizing react/typescript. Here's the react router configuration: const Root = () => ( <> <NavBar/> <Router> <Route path="/" component={Home} /> <Route ...

Certain Array properties cause Array methods to generate errors

I am working with an Array prop in my component's props that is defined like this props: { datasetsList: { type: Array as PropType<Array<ParallelDataset>>, required: false } }, Within the setup() method of my component, I have ...

What is the best approach to converting an array of strings into a TypeScript type map with keys corresponding to specific types?

The code provided below is currently working without any type errors: type Events = { SOME_EVENT: number; OTHER_EVENT: string } interface EventEmitter<EventTypes> { on<K extends keyof EventTypes>(s: K, listener: (v: EventTypes[K]) => voi ...

An issue arises when attempting to write to the database specifically when the model is imported from a separate file

There seems to be an issue with saving the model to the database when it's imported from another file. The error message received is: MongooseError: Operation users.insertOne() buffering timed out after 10000ms at Timeout. (/var/www/bhp_2/server/nod ...