typescript 使用KeyValuePipe时 *ngFor中出错:国家旅游局(2322)

kb5ga3dv  于 2023-01-10  发布在  TypeScript
关注(0)|答案(2)|浏览(131)

我有以下类型

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出了问题。

5q4ezhmt

5q4ezhmt1#

只需像这样更改它

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

oxcyiej72#

该问题与父母的打字操作有关,应采取以下措施:

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

这个问题是children对象类型化过程中的一个过度复杂的问题。
问题在于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,这样做意味着我们获得了存储在原始对象中的值,这是因为keyvalue*ngFor组合在一起修改了对象,导致它失去了可迭代性并引发错误。

相关问题