Creating a string array within an array in TypeScript

Struggling to return a type-safe Typescript v3.5 array without having to declare it within the method body? This array should consist of multiple string arrays.

Desiring something along the lines of:

 foo(): Array<Array<string>>:
    // perform some action

    return new Array<Array: string>>

Extra challenge: How can you return an array that contains arrays without explicitly declaring all those arrays in the code body?

LATEST UPDATE:

foo(): Array<Array<string>> {
    // determine 'someSize' and 'anotherSize'
    // initialize both arrays:
    let tempPartOfSpeechArr: string[] = new Array(someSize);
    let tempLinguisticUsageArr: string[] = new Array(anotherSize);

    let arrContainer = new Array(2);
    arrContainer[0] = tempPartOfSpeechArr;
    arrContainer[1] = tempLinguisticUsageArr;


    return arrContainer;

I just aim to return the arrContainer with both arrays inside. Trying to keep the code concise while maintaining readability.

Answer №1

If you want to quickly return an array literal, you can simply do so:

foo(): Array<Array<string>> {
    // Calculate 'someSize' and 'anotherSize'
    // Initialize both arrays:
    let tempPartOfSpeechArr: string[] = new Array(someSize);
    let tempLinguisticUsageArr: string[] = new Array(anotherSize);

    return [tempPartOfSpeechArr, tempLinguisticUsageArr]; // <===================
}

This method should be clear for those who are familiar with TypeScript. :-)


A quick note: Avoid using new Array or defining the length of your arrays unless necessary. You can simplify these lines:

let tempPartOfSpeechArr: string[] = new Array(someSize);
let tempLinguisticUsageArr: string[] = new Array(anotherSize);

by writing them like this:

let tempPartOfSpeechArr: string[] = [];
let tempLinguisticUsageArr: string[] = [];

The only difference is that creating sparse arrays in the original code (arrays with a defined length but no elements) can impact JavaScript engine optimizations.


Another note: It seems you're mixing two different styles of type declarations for arrays. While foo's return type is Array<Array<string>>, you declare arrays using string[]. You might consider using consistent array syntax by declaring foo as string[][]:

foo(): string[][] {
    // ....

For a complete example (check it out on the playground), here's a sample returning an array with unique non-digits and digits from a string:

function ex(str: string): string[][] {
    const a: string[] = [...new Set(str.replace(/\d/g, ""))];
    const b: string[] = [...new Set(str.replace(/\D/g, ""))];
    return [a, b];
}
console.log(ex("Testing 1 2 3 testing"));
// =>
// [
//   ["T", "e", "s", "t", "i", "n", "g"],
//   ["1", "2", "3"]
// ]

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

Sometimes, Express may return the message "not found" on and off

After working with express for many years, I find myself a bit out of practice with TypeScript - and it seems like my eyesight is failing me! This is the first time I've encountered this issue, so I must be missing something... My current dilemma is ...

Issue occurs where the system is unable to recognize a defined variable, despite it being clearly defined

I keep encountering an error message stating that my variable is not defined, even though I have clearly defined it just a few lines above where the error occurs. The reason behind this error is baffling to me, as I cannot identify any potential triggers ...

Merging JSON data with Arrays using TypeScript within the context of Ionic 3

Attempting to embed data as a string within an access modifier (public pieChartLabels) that is an array has been challenging. Despite successfully retrieving the expected data from the provider using console.log, integrating it with the modifiers has prove ...

TypeScript(error:2532): object may be undefined despite null or undefined check

Currently, I am developing a Discord-bot using TypeScript which includes a command to retrieve information from an airport. To do this, users only need to provide the 4-character ICAO code that identifies the specific airport. However, due to potential use ...

Here's how to use the useState hook directly in your React components without

Currently, I am using the code snippet below to import useState: import * as React from 'react' import {useState} from 'react' I wanted to see if there is a way to condense this into one line, so I attempted the following: import * a ...

Angular - The aftermath of subscribing

I have been attempting to use subscribe to return a value to this.voucherDetails, but unfortunately, it doesn't seem to be working as expected. Below is the code snippet for the getVoucherDetails function which includes the subscribe method. voucher ...

Creating an npm library using TypeScript model classes: A step-by-step guide

Currently, I am working on a large-scale web application that consists of multiple modules and repositories. Each module is being developed as an individual Angular project. These Angular projects have some shared UI components, services, and models which ...

Unleashing the power of await with fetch in post/get requests

My current code has a functionality that works, but I'm not satisfied with using it. await new Promise(resolve => setTimeout(resolve, 10000)); I want to modify my code so that the second call waits for the result of the first call. If I remove the ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Establishing properties while creating a fresh instance of a class

I am currently working on developing an invoice application using TypeScript. In my project, I have created an Invoice class with several properties and objects. However, when attempting to set the properties of an item object within the Invoice class usin ...

How to Utilize an Array from Observable Object in Angular 2 with ngFor and Async Pipe

I am currently learning about the utilization of Observables in Angular 2. Here is a snippet of code from a service I am working with: import {Injectable, EventEmitter, ViewChild} from '@angular/core'; import {Observable} from "rxjs/Observab ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

What is the best way to transfer an object to a component through Angular routing?

In my "home" component, I have an array called mangas containing a list of objects that I iterate through like this: <div *ngFor="let manga of mangas"> <h1> {{ manga.title }} </h1> <button routerLink="/manga/{{ man ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

Tips on Identifying the Category

I am currently studying TypeScript. Recently, I have been using Axios to fetch API data, and then I stored the returned value in a useEffect hook. However, when trying to display it on the screen, I encountered an error stating that there is no 'name ...

What causes tsc to generate different json files based on its execution location?

Scenario: You have a typescript project set up to generate JSON files. The tsconfig.json is properly configured and all dependencies are in place. You've even referred to this related Q&A and ensured that your typescript files are importing the json f ...

Tips for resolving the React(TypeScript) issue "Invalid hook call."?

I received an error message stating: "Invalid hook call. Hooks can only be called inside of the body of a function component." within my React function: interface Items { items: any[] } const [items, setItems] = useState<Items>(); const ItemsList ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

Custom Mapped Types in TypeScript

I'm currently exploring ways to create a custom type that will convert the properties of an object from type Vector to type Array. This is what I have so far type ToArray<T> = { [P in keyof T]: T[P] extends Vector<any> ? Array<any ...