[英]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.