What is the best way to initialize an array with values in a Typescript constructor?

I've attempted the following:

class PhraseService

    phrasePosShortNames: [{ id: number, name: string }];
    phrasePosNames = [
        {
            id: 0,
            longName: '#',
            shortName: '#'
        },
        {
            id: 1,
            longName: 'Noun',
            shortName: '#'
        },
        {
            id: 2,
            longName: 'Verb',
            shortName: 'V'
        }
    ];
    
    constructor( ) {

        this.phrasePosShortNames = this.phrasePosNames.map(item => {
            id: item.id,
            name: item.longName
        })
    }

However, I encounter an error:

Severity Code Description Project File Line Suppression State Error TS2322 Type 'void[]' is not assignable to type '[{ id: number; name: string; }]'. Property '0' is missing in type 'void[]'

Could someone please point out my mistake?

Answer №1

this.words.map(word => {
    return {
      num: word.num,
      term: word.fullTerm
    };
});

The data structure should be

{ num: number, term: string }[]

or

Array<{ num: number, term: string }>

I believe using an interface would enhance the readability of the code.

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

Remove any extra spaces at the end of a copied number when using Angular

Is there a way to automatically remove spaces at the end of a 10-digit number when it is copied from another source (like email or Word documents) and pasted into the search bar? Currently, this function only works when we press enter. I would like for bl ...

What is the most efficient method for transforming files using a heroku deployed application?

I'm currently developing a Discord bot deployed on Heroku that has a function to convert video files to .mp4 format and then embed the file in a reply message. When running the function locally, everything works fine. However, when running it on the d ...

Is there a way for me to retrieve the text generated by OpenAI in the completion response?

let gptResponse = await openai .createCompletion({ model: "davinci", prompt, max_tokens: 60, temperature: 0.9, presence_penalty: 0, frequency_penalty: 0.5, best_of: 1, n: 1, stre ...

The joinAndSelect function in NestJS is having trouble fetching all the data from the PostgreSQL database

In my database, I have three tables named product, branch, and product_branches. The product table contains columns: id, name The branch table contains columns: id, name, lat, lng And the product_branches table contains columns: productId, branchId I w ...

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

What is the best way to extract all Enum Flags based on a Number in TypeScript?

Given: Enum: {1, 4, 16} Flags: 20 When: I provide the Flags value to a function Then: The output will be an array of flags corresponding to the given Enum: [4, 16] Note: I attempted to manually convert the Enum to an array and treat values as numb ...

The required property 'intersect' is not found in the type 'import("cesium").BoundingSphere'

Incorporating Cesium into a ReactJs application has been my recent project. I have successfully displayed various factories in the cesium viewer and drawn polygon grids on their coordinates. However, I am encountering confusion with one particular aspect. ...

Alert an Angular 2 component about changes triggered by a service

Currently working with Angular 2 and utilizing an AuthService for authentication. I am at a crossroads on how to effectively inform other components when a user logs in or out. Seeking advice on the best approach for managing this situation. Any insights ...

Issues arise when certain features in the Typescript 3+ version do not seem to be functioning properly, despite being installed

I have globally installed Typescript version 3.7.3 and Visual Studio Code is using the same version, yet I am unable to access functionality specific to Typescript 3+. For example, when trying to declare a variable with the type "unknown", I encounter a co ...

An error occurred while attempting to set up Next-auth in the process of developing

In my Next.js app, I have implemented next-auth for authentication. During local development, everything works fine with 'npm install' and 'npm run dev', but when I try to build the project, I encounter this error message: ./node_modul ...

Resolving the Duplicate Identifier Issue in Ionic 2 with Firebase Integration

I'm struggling with setting up ionic2 + Firebase 3. Following a tutorial, I installed Firebase and Typings using the commands below: npm install firebase --save npm install -g typings typings install --save firebase However, when I try to run ioni ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

The variable ApiAIPromises is not recognized within the context of Ionic 3 and Dialogflow

I am currently integrating dialogflow into my ionic app. Below is the code snippet from my .ts file: import { Component, NgZone } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; declare v ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

What is the syntax for declaring a state variable as a Set data type in programming?

Struggling to establish a state variable in React using Typescript. Encountering an error when attempting to specify its type as Set. The purpose of this variable is to contain an array of objects. const [blocksList, setBlocksList] = useState<Set>([ ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

There seems to be an issue with the React app where the fetch() response is coming back empty. Strangely enough, when sending

Below is the code for my API call: export async function getTasks(): Promise<Task[]> { if (process.env.NODE_ENV === "test") { return new Promise<Task[]>((resolve) => setTimeout(() => resolve(DefaultTasksArray), 1500) ...

Declarations for TypeScript in NPM packages

In order to streamline my development process with bun.sh using workspaces as npm packages, I have created a tool available here. However, I am facing two issues: After bun installing the 'core' packages from npm and testing a sample, I encounte ...

Dragging and dropping elements onto the screen is causing them to overlap when trying

I am having trouble merging the drag and drop functionality from Angular Material with resizing in a table. Currently, both features are conflicting and overlapping each other. What I am hoping for is to automatically cancel resizing once drag and drop s ...

Utilize JQuery to choose the angular element

Can Angular tags be selected using JQuery? I am currently utilizing the ui-select Angular component, which is integrated into the HTML page as shown below: <ui-select ng-model="rec.currencyCode" on-select="ctrl.selectCurrencyCode(rec, $item)"> & ...