繁体   English   中英

*ngFor 与 KeyValuePipe 错误:ngtsc(2322)

[英]Error in *ngFor with KeyValuePipe: ngtsc(2322)

我有以下类型

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

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

也就是说,内部child对象{ parent, key }安装在树结构中,在它们的下面。 父母; 允许所有parent-child配对。 例如检查

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

现在,如果我在 Angular 模板中使用parents

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

我得到错误

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)

当然这可以使用$any()来解决,但显然我的类型或KeyValuePipe有问题。

这个问题与父母的打字有关,以下应该有效:
 type Parents = { [parentKey in ParentKeys]: { children: { parent: ParentKeys, key: ChildKeys }[]; }; };

问题是孩子 object 的打字过于复杂。

问题在于自己的键值keyvalue*ngFor交互。

以下html作品:

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

主要的不同是我们调用parents[parent.key]而不是我们调用parent.value 这样做意味着我们获得了原始 object 中存储的值。这是因为键值结合*ngFor修改了keyvalue ,导致其失去了可迭代性并引发了错误。

像这样简单地改变它

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM