Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service:

{
    de49e137f2423457985ec6794536cd3c: {
        productId: 'de49e137f2423457985ec6794536cd3c',
        title: 'item 1',
    },
    d6623c1a2b843840b14c32685c212395: {
        productId: 'd6623c1a2b843840b14c32685c212395',
        title: 'item 2',
    },
    ids: [
        'de49e137f2423457985ec6794536cd3c',
        'd6623c1a2b843840b14c32685c212395',
    ],
}

This response object contains an array of item ids string[] and an index signature [id: string]: Item.

Trying to define this in Typescript is proving tricky because having both the index signature and array together in one interface causes issues. For instance:

interface ItemList {
    [id: string]: Item;
    ids: string[];
}

I understand that when using an index signature, all other properties need to have the same type. As I navigate through Typescript, I am uncertain about how to handle this data structure without extracting the ids out of the item object.

interface ItemList {
    [id: string]: Item;
    ids: string[];
}
interface Item {
    productId: string;
    title: string;
}

const item: ItemList = {
    de49e137f2423457985ec6794536cd3c: {
        productId: 'de49e137f2423457985ec6794536cd3c',
        title: 'item 1',
    },
    d6623c1a2b843840b14c32685c212395: {
        productId: 'd6623c1a2b843840b14c32685c212395',
        title: 'item 2',
    },
    ids: [
        'de49e137f2423457985ec6794536cd3c',
        'd6623c1a2b843840b14c32685c212395',
    ],
};
console.log(item.ids.map((id: string) => item[id]));

Error Message

The property 'map' is not found on type 'Item | string[]'.

The property 'map' is not found on type 'Item'.

Answer №1

To resolve this issue, you can utilize an intersection type:

type ListOfItems = {
    [key: string]: Item;
} & {
    keys: string[];
}
interface Item {
    id: string;
    name: string;
}

const itemsList: ListOfItems = Object.assign({ // You cannot directly create the object
    abc123: {
        id: 'abc123',
        name: 'Item A',
    },
    xyz456: {
        id: 'xyz456',
        name: 'Item B',
    }
}, {
    keys: [
        'abc123',
        'xyz456',
    ],
});
console.log(itemsList.keys.map((key: string) => itemsList[key]));

The intersection type allows for the combination of inconsistent named properties with indexers. (It should be noted that while not strictly type-safe because items['keys'] does not return an Item as expected, it appears to be a fair compromise in this scenario)

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

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

Tips for importing a file with a dynamic path in Angular 6

I'm facing an issue where I need to import a file from a path specified in a variable's value. For example, it looks like this: let test = require(configurationUrl); Here, configurationUrl represents a path such as '../../assets/app.conf.j ...

Exploring table iteration in Angular 7

I am looking to create a table with one property per cell, but I want each row to contain 4 cells before moving on to the next row... This is what I want: <table> <tr> <td> <mat-checkbox>1</mat-checkbox& ...

Troubleshooting the creation of migration paths in NestJS with TypeORM

After diligently studying the NestJS and TypeORM documentation, I have reached a point where I need to start generating migrations. While the migration itself is creating the correct queries, it is not being generated in the desired location. Currently, m ...

Applying the spread operator in the map function for copying objects

In my Angular application, I am attempting to copy an object and add a new property using the spread operator. To add the new property, I have created a method called 'addNewProperty(name)' which returns the property and its value. However, when ...

Guide on inserting tooltip to designated header column in primeNG data table

Html <p-table #dt1 [columns]="cols" [value]="cars1"> <ng-template pTemplate="header" let-columns> <tr> <th *ngFor="let col of columns"> {{col.header}} </th> ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

Obtain the input value from a modal and receive an empty string if no value

Utilizing ng-multiselect-dropdown within my bootstrap modal allows users to choose multiple products. Each time an item is selected (onItemSelect), a new div is inserted using the jQuery method insertAfter(). This new div displays the quantity of the selec ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

gulp-tsc cannot locate the src directory

I am currently working on developing a .NET Core application using Angular2, but I keep encountering the following error: /wwwroot/NodeLib/gulp-tsc/src/compiler.ts' not found. I'm having trouble pinpointing what I might be missing. tsconfig.js ...

After installing Highcharts, an error occurs stating 'Highcarts is not defined'

I am trying to incorporate Highcharts into an Angular 5 project using the ng2-highcharts npm package. However, I keep encountering an error stating that 'highcharts is not defined'. In my Angular 5 project, I have integrated Highcharts and utili ...

What are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

Utilizing Angular 4 with Ahead-Of-Time compilation in combination with Electron, as well as

I am new to Angular/Typescript and currently developing a cross-platform Desktop application with Electron and Angular 4. My current challenge involves using a Service in different components, but I need this service to be loaded from a separate file based ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...

Converting React to Typescript and refactoring it leads to an issue where the property 'readOnly' is not recognized on the type 'IntrinsicAttributes & InputProps & { children?: ReactNode; }'

I'm currently in the process of refactoring an application using Typescript. Everything is going smoothly except for one particular component. I am utilizing the Input component from the library material-ui. import {Input} from "material-ui"; class ...

The value of an Angular array seems to be disappearing after being copied to another array and then cleared

I have encountered an issue while working with arrays. I am initializing two arrays - one with some values and another as empty. However, when I assign the items from the first array to the second array and then clear the first array, it unexpectedly clear ...

Creating a custom utility type in TypeScript for serializing an array of objects: What you need to know

Imagine I have the following specified object: type Test = { date: Date num: number str: string } In this object, there is a Date type that needs to be converted into a string ("serialized"). To achieve this, I came up with the concept of a Generic ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

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 ...