Issue encountered in *ngFor utilizing KeyValuePipe: ngtsc(2322)

In my scenario, I have two categories:

type ParentKeys = "mum" | "dad";
type ChildKeys = "alice" | "frank";

type Parents = {
    [parentKey in ParentKeys]: {
        children: {
            [childKey in ChildKeys]: {
                parent: parentKey;
                key: childKey;
            };
        }[ChildKeys][];
    };
};

This structure organizes the inner child objects { parent, key } into a tree-like format under their respective parents, accommodating all possible parent-child combinations. For an example, refer to this snippet:

const parents: Parents = {
    mum: {
        children: [
            { parent: "mum", key: "alice", },
        ],
    },
    dad: {
        children: [
            { parent: "dad", key: "frank", },
            { parent: "dad", key: "alice", },
        ],
    },
};

When utilizing the parents object within an Angular template,

<div *ngFor="let parent of parents | keyvalue">
    <div *ngFor="let child of parent.value.children">
        <div>child {{child.key}} of parent {{child.parent}}</div>
    </div>
</div>

An error is raised:

Type
'(
    { parent: "mum"; key: "alice"; } |
    { parent: "mum"; key: "frank"; }
)[] |
(
    { parent: "dad"; key: "alice"; } |
    { parent: "dad"; key: "frank"; }
)[]'
is not assignable to type
'(
    (
        { parent: "mum"; key: "alice"; } |
        { parent: "mum"; key: "frank"; }
    )[] &
    NgIterable<
        { parent: "mum"; key: "alice"; } |
        { parent: "mum"; key: "frank"; }
    >
) | null | undefined'
.ngtsc(2322)

To circumvent this issue, one could resort to using $any(). However, it indicates a potential problem with either the types or the functionality of the KeyValuePipe.

Answer №1

The problem stems from the typing used in the parent objects, and the solution is as follows:
type Parents = {
    [parentKey in ParentKeys]: {
        children: {
            parent: ParentKeys, key: ChildKeys
        }[];
    };
};

The original issue was due to an overly complex typing of the children object.

The issue arises from how the keyvalue pipe interacts with *ngFor.

The following snippet of html resolves the issue:

<div *ngFor="let parent of parents | keyvalue">
  <div *ngFor="let child of parents[parent.key].children">
    <div>child {{ child.key }} of parent {{ child.parent }}</div>
  </div>
</div>

The key difference is that instead of using parent.value, we use parents[parent.key]. This allows us to access the original value stored in the object. The combination of keyvalue and *ngFor alters the object and can lead to loss of iterability and errors.

Answer №2

modify it in this manner

declare type Family = {
  [familyHead in FamilyHeads]: {
    descendants: Array<{
      parent: FamilyHeads;
      childKey: DescendantKeys;
    }>;
  };
};

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

Problems encountered with iframe-resizer in Next.js: Notification of GPLv3 License and Error message indicating "iFrame not responding"

My project in Next.js 14 involves creating a testimonial feature with testimonials displayed through an iframe. The aim is to generate an iframe tag (and potentially necessary script tags) that, when inserted into any website's HTML, allows users to v ...

The button is obscured by the dropdown menu

Here is the code snippet I am working with: HTML <nav class="navbar bg-dark navbar-dark"> <div class="container-fluid"> <div class="navbar-header"> <a href="#" class=&quo ...

Tips for concealing a react bootstrap modal while simultaneously executing the save function

When I click on the button with the onClick event set to {this.props.onHide}, the Modal is hidden successfully. However, I also need to execute the save function. When I try calling the save function along with the props, the save function is executed but ...

`Square payment integration using the mean stack technology stack`

Seeking advice on how to integrate Square payment form with angular and node. The form functions properly, but upon hitting send, it fails to post to /process-payment. As a newcomer to the MEAN stack, I am unsure where to start regarding using angular and ...

Oops! The program encountered an issue where it couldn't access the "Point" property because it was undefined. This occurred while working with openlayers 3 and jsts on

I am currently working on implementing a buffer function for some features that have been drawn on a map following this particular example. However, I am encountering the following error: ERROR TypeError: Cannot read property 'Point' of undefin ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

How can I showcase an image using Angular?

Recently, I've started working with Angular and I'm trying to display images using assets. I have a service that looks like this: const IMAGES = [ {"id":1, "category": "boats", "caption": "View from the boat", "url":"assets/img/boat_01.jpeg"}, ...

React application experiencing freezing when setInterval function is utilized

I've been working on incorporating Conway's Game of Life into a React project, but I'm encountering freezing issues whenever a new generation is triggered. My assumption is that the problem lies in the excessive overhead from constant DOM re ...

Encountering difficulties while attempting to transition from angular 9 to angular 10

I attempted to upgrade my Angular project by running the following commands: $ ng update @angular/core@9 @angular/cli@9 $ ng update @angular/core @angular/cli However, when I executed the last command in the console, it resulted in an error message: Your ...

Discover a Simple Trick to Enhance tsc Output: Unveil the Art of

When I work on a TypeScript project, I typically use the watch mode of the compiler: tsc --watch However, one issue I face is that it's challenging to identify errors in the output since they are displayed as plain text: Sometimes I don't even ...

"Concealing a column in a PrimeNG data table with dynamic columns: A step-by-step

Hi, I'm looking for a way to hide a column in my PrimeNG data table. Is there an attribute that can be used to turn off columns in PrimeNG data tables? .Html <p-dataTable emptyMessage="{{tbldatamsg}}" [value]="dataset" scrollable="true" [style]=" ...

Error in inferring argument types for a generic interface function in Typescript

Unique interface export interface DataService { getByTypeId<T extends number | string>(id: T): Promise<SomeType>; } Additionally, the implementation export class BService implements DataService { async getByTypeId(id: number): Promise&l ...

Leveraging getStaticProps in Next.js

I am currently embarking on my inaugural Nextjs project, focused on developing a basic blog utilizing the JSON placeholder API. Strangely, I am encountering an issue where the prop "posts" is being perceived as undefined. Can anyone provide assistance with ...

The 'current' in react typescript is not found within the type 'never'

Currently, I am working with react and typescript in my project. To fetch the height of a specific div tag, I decided to utilize useRef method. However, when trying to access 'current' property, TypeScript throws an error. Property 'current& ...

Can we guarantee that the key and its corresponding value are both identical strings in Typescript?

Is it possible to enforce the key of a Record to be the same as the inner name value in a large dataset? interface Person<T> { name: T title: string description: string } type People = Record<string, Person<string>> // example dat ...

There is an issue with the Angular 2 provider when attempting to use useValue in conjunction with a function call

I can't figure out why the syntax for Angular 2 providers isn't functioning as expected when trying to provide a specific value using the useValue field. For example, in my app.module.ts file: // Abstracted base class (since interfaces don&apos ...

Exploring the Possibilities of OpenLayers with Scalable Vector

Trying to create a webpage with an image that can be navigated using drag and scroll events, similar to Google Maps. Instead of building it from scratch, I attempted to achieve this using OpenLayers, with the intention of using the image in place of a map. ...

NextJS API Generator for OpenAPI specifications

In my NextJS project, we utilize the /api path to implement our API, with an openapi.yaml file defining the interface. To generate the API client successfully, we run the following command: openapi-generator-cli generate -i data/api/openapi.yaml -o src/api ...

I'm having trouble with Material Design Slide Toggle as it lacks event.StopPropagation functionality. Any suggestions on what alternative I

When working with the Slide Toggle in Material Design, I noticed that it does not have a stopPropagation event. This is because the "MdSlideToggle.prototype._onChangeEvent" already includes a call to stopPropagation. So, what should be used instead? <m ...

Steer clear of using Typescript to exclude certain sections of code from compilation

Is there a method to prevent certain code from being compiled by the Typescript compiler based on a variable that needs to be provided in the compiler command? This would be beneficial for developing multi-platform applications where the code is mostly sim ...