Javascript 将两个不同类型的响应合并到一个列表中
我需要将两个不同的响应组合成一个,它们共享一个共同的键/值对,即距离。我需要将这两个json对象组合成一个。按距离排序。 我已经尝试过这样做:Javascript 将两个不同类型的响应合并到一个列表中,javascript,typescript,Javascript,Typescript,我需要将两个不同的响应组合成一个,它们共享一个共同的键/值对,即距离。我需要将这两个json对象组合成一个。按距离排序。 我已经尝试过这样做: const test: [Group, Profile] = [].concat(profiles, groups) export type Profile = { userId: string imageId: string firstname: string middleName: string lastname: string
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
有点尴尬,因为它假定参数具有相同的类型,但您可以通过分散数组来优雅地执行:[…profiles,…groups]
请注意,[Group,Profile]
不是结果的正确类型,因为这是一个长度为2的数组,包含组和配置文件。相反,您可以使用组
和配置文件
的并集数组,如下所示:
type ProfileOrGroup = Profile | Group
const test: ProfileOrGroup[] = [...profiles, ...groups]
删除类型批注。它同时是不正确的(应该是(Group | Profile)[
)和不必要的,因为推断的类型正是您想要的。而且,空数组是无意义的——只需写const test=groups.concat(profiles)代码>或<代码>常量测试=[…组,…配置文件]代码>