Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将两个不同类型的响应合并到一个列表中_Javascript_Typescript - Fatal编程技术网

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

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

我需要将两个不同的响应组合成一个,它们共享一个共同的键/值对,即距离。我需要将这两个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
有点尴尬,因为它假定参数具有相同的类型,但您可以通过分散数组来优雅地执行:
[…profiles,…groups]

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

type ProfileOrGroup = Profile | Group

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

删除类型批注。它同时是不正确的(应该是
(Group | Profile)[
)和不必要的,因为推断的类型正是您想要的。而且,空数组是无意义的——只需写
const test=groups.concat(profiles)或<代码>常量测试=[…组,…配置文件]