Tips for making a dictionary list in TypeScript

Initially, one might attempt the following:

interface Port_Mapping {
  number: Port_role
}
port_mappings: Port_Mapping[{number: Port_role}] = [];

However, an error is encountered stating:

Type '{ number: Port_role; }' cannot be used as an index type.

Another approach could involve:

interface Port_Mapping {
  number: Port_role
}

port_mappings: Port_Mapping[] = [];

this.port_mappings.push({5: Port_role.input})

Yet, this also poses an issue as the 'number' in the interface is considered a name rather than a type, leading to:

Argument of type '{ 5: Port_role; }' is not assignable to parameter of type 'Port_Mapping'. Object literal may only specify known properties, and '5' does not exist in type 'Port_Mapping'.

In my scenario, I aim for a series of dictionaries where each dictionary follows the structure:

[{key1: value1, key2: value2, key3: value3}]

Answer №1

Attempt

declaration Port_Map {
  [index: number]: Map_location
}

The [index: number] serves as an indexer - specifically used within interfaces to enable indexing of the object instance.

Initially, your declaration in TS may seem unclear. You are defining a variable port_mapping with type Port_Mapping, indexed by an object instance {number: Port_role}, where the value assigned to the number property is of the interface type Port_role.

In your second attempt, you are aiming to insert an object instance {5: Port_role.input} into an array of type Port_Mapping. This results in an evident type inconsistency, as the object being inserted lacks a number property (and the target array type (Port_Mapping) does not have a "5" property).

Example:

interface Dictionary {
  [idx: number]: string
}

const ind = 5;
const dicti: Dictionary = { 1: 'abc', [2]: 'def', [ind]: 'ghi' };
dicti[7] = 'jkl';
dicti[ind] = 'mno';
delete dicti[2]; // removes the entry at index 2: 'def'

const listOfDicts: Dictionary[] = [dicti, { 1: 'a', [2]: 'b', [ind]: 'c'}];
listOfDicts.push({ 1: 'a', [2]: 'b', [ind]: 'c'});

Answer №2

One effective method is to employ a TypeScript Record, as detailed in this resource

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

Generating a JavaScript bundle using the npm TypeScript compiler

Is there a way to compile TypeScript source files into one JavaScript bundle file? We have developed a tool on node.js and are currently using the following TypeScript compilation code: var ts = require('typescript'); ... var program = ts.creat ...

In Angular, is there a way to transform time into the format of YYYY-MM-DDThh:mm:ssTZD?

Our backend is built with Java and we are using the ISO 8601 standard for date formatting. In order to pass dates in this format, I require a method to convert the date into the specified format. In Java, we use: DateFormat iso8601 = new SimpleDateFormat( ...

Unable to locate identifiers 'Let' (TS2304), 'headers' (TS2552), and 'options' in a TypeScript script

I am new to using Angular and Ionic. While following a tutorial, I encountered the following errors: Cannot find name ‘Let’ (TS2304) Cannot find name ‘headers’. Did you mean ‘Headers’? (TS2552) Cannot find name ‘options’. Did you mean ‘ ...

Getting just the outer edges of intricate BufferGeometry in Three.js

Currently, I am immersed in a project that involves zone creation and collision detection using Three.js. The primary objective is for my application to effectively manage collisions and produce a BufferGeometry as the final output. My aim is to visually r ...

What steps should be taken to properly utilize the useRef hooks in this code snippet?

I've been working on a beer wishlist project using React. However, I encountered an issue with the following error message: TS2786: 'EditBeerPage' cannot be used as a JSX component. Its return type 'Element | undefined' is not a ...

ElasticSearch - delayed indexing update underway

Utilizing the elasticsearch module in typescript, I've encountered an issue where changes made to indexes or newly inserted documents are not being detected by the code... Below is an example: try { await this._client.indices.de ...

Invalidity of types occurs when dispatching data to redux

My reducer code is as follows: import { profileAPI } from '../api/api' import shortid from 'shortid' const ADD_POST = 'profile/ADD-POST' const SET_USER_PROFILE = 'profile/SET_USER_PROFILE' const SET_STATUS = 'p ...

Webpack compatibility issue hindering big.js node module functionality

I'm currently working on compiling (typescript files) and bundling my source code using webpack. Below is the content of my webpack.config.js file: const path = require('path') module.exports = { devtool: 'eval-source-map', en ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

Unable to see Next.js page in the browser window

I have set up a next.js project with App Router and my file structure under the app folder looks like this: *some other files* . . user | [id] | | page.tsx | @users | | page.tsx | layout.tsx | page.tsx I am ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

Generate a table in MongoDB using NestJs without the need to create a new collection

I am facing a challenge with my app where I need to create an order with multiple attributes, one of which is an array of ordered products. Each object in the orderedProduct array must include the productId and the amount. However, I do not want to create ...

Managing sessions in Typescript using express framework

Hey there, I'm just starting to learn about TypeScript and I have a question about how sessions are handled in Typescript. Could someone please explain the process of session initialization, storing user data in sessions, etc.? If you have any tutoria ...

How to retrieve a component's property within an Angular2 provider?

As a beginner in OOP, I am currently experimenting with Ionic 2, Angular 2, and TypeScript. In my home.html file, I have an input field connected to the username property in home.ts as shown below: export class HomePage { public username: string; public n ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

Production environment sees req.cookies NEXTJS Middleware as undefined

Here is my latest middleware implementation: export async function middleware(request: NextRequest) { const token = request.headers.get('token') console.log(token) if (!token || token == undefined) { return NextResponse.redirect(new URL('/lo ...

Is it possible to include a JavaScript reference to an external .d.ts file?

Our online js library (written in pure javascript) is in need of a .d.ts reference to provide users with Intellisense in VS Code without the need for any downloads or installations. ...

Error: The function crypto.createHmac doesn't exist

I've been attempting to run integration tests and keep encountering the following error: 2022-03-26T18:51:12.446Z cypress:network:agent got family { family: 4, href: 'https://wepapi.com/api/session-status' } 1) "before all" hook for "shoul ...

Creating a fresh ngx-translate pipeline (comparing pure and impure methods)

Edit: I am looking to enhance the functionality of ngx-translate's pipe by extending it. Here is an example of how I achieved this: import { Pipe, PipeTransform } from '@angular/core'; import { TranslatePipe } from "@ngx-translate/core"; @ ...

I am facing an issue in my Vue component where the function this.$refs.myForm.validate is not recognized

The validation messages are correctly displayed when the rules function as expected. The button's disabled state is determined by the value of this.valid, which changes depending on the outcome of the checkTextBoxValidation method called upon each inp ...