繁体   English   中英

将两个不同 typescript 类型的响应合并到一个列表中

[英]Combine two responses both different typescript types in one list

我需要将两个不同的响应合并为一个,两者共享一个共同的键/值对,距离。 我需要将这两个 json 对象合并为一个。 按距离排序。 我试过这样做是这样的:

const test: [Group, Profile] = [].concat(profiles, groups)

export type Profile = {
  userId: string
  imageId: string
  firstname: string
  middleName: string
  lastname: string
  distance: number
}

export type Group= {
  groupId: string
  name: string
  distance: number
}

这可能吗? 我收到一个错误:

“Profile[]”类型的参数不能分配给“ConcatArray”类型的参数。

使用concat有点尴尬,因为它假定 arguments 具有相同的类型,但是您可以通过传播 arrays: [...profiles, ...groups]来优雅地做到这一点。

请注意, [Group, Profile]不是结果的正确类型,因为这是一个长度为 2 的数组,其中包含一个Group和一个Profile 相反,您可以使用GroupProfile的并集数组,如下所示:

type ProfileOrGroup = Profile | Group

const test: ProfileOrGroup[] = [...profiles, ...groups]

TypeScript操场

暂无
暂无

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

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