[英]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.