我期望参数类型为 Array<A | B>
接受 Array<A>
和Array<B>
。但事实并非如此,为什么?
export type A = {
id: string;
name: string;
legacyId?: number;
};
export type B = {
id: number;
title: string;
};
export type AOrB = A | B;
function toB(items: Array<B>): Array<B> {
return items
.reduce((acc, item) => {
if (typeof item.id === 'number') {
const b = ((item:any):B);
return [...acc, b];
} else if (typeof item.id === 'string') {
const a = ((item:any):A);
return a.legacyId ? [...acc, {
id: a.legacyId,
title: a.name,
}] : acc;
}
return acc;
}, []);
}
function onUpdateItem(items: Array<B>) {
//...
}
function updateItem(items: Array<A>) {
onUpdateItem(toB(items));
}
最佳答案
Array<A | B>
表示可以容纳 A
的数组或B
s。
Array<A>
不是Array<A | B>
,因为它不能容纳 B
s(如果你在其中放入 B
会发生什么?)。
这称为不变性。
关于javascript - 联合泛型类型的行为应该是什么,例如 Array<A | B>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45467997/