[英]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
。 相反,您可以使用Group
和Profile
的并集数组,如下所示:
type ProfileOrGroup = Profile | Group
const test: ProfileOrGroup[] = [...profiles, ...groups]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.