typescript - TypeScript – 对象数组联合的值产生交集,而不是联合
问题描述
有两个不同对象的数组(数组a
和数组b
),这些数组的联合的成员值 - (a | b)[number]
- 产生它们的交集,而我希望有一个联合:
type a = { one: string }[];
type b = { one: string, two: string }[];
type ab = (a | b)[number]; // actual type: { one: string }
// expected type: { one: string } | { one: string, two: string }
另请参阅TypeScript playground 的链接。
我想知道:
- 派生类型
{ one: string }
是否正确? - 为什么不是
{ one: string } | { one: string, two: string }
? - 有没有办法实现
expected
任意对象数组的类型?
谢谢!
解决方案
是的,派生类型是正确的,但通常不是预期的。
这就是联合在 TS 中的工作方式。
考虑下一个例子:
type a = { one: string };
type b = { one: string, two: string };
type ab = keyof (a | b); // "one"
TS 将返回one
,因为此密钥可在两种类型(a,b)之间共享。
为了实现所需的行为,您可以尝试分布式条件类型:
当条件类型作用于泛型类型时,它们在给定联合类型时变得可分配
type a = { one: string }[];
type b = { one: string, two: string }[];
type ArrayValues<T> = T extends Array<infer Elem> ? Elem : never
type Result = ArrayValues<a | b> // { one: string } | { one: string, two: string }
推荐阅读
- python - 在 discord.py 中保存数据
- azure-iot-hub - 具有自定义文件名格式的 ADLS Gen2 的 Azure IoT 中心端点
- wordpress - 使用 wp-cli 变量嵌套 if-then 语句
- python - 在 Librosa 中获取与 STFT 相关的频率
- c# - 为什么 Avicap32.capCreateCaptureWindow 关闭?
- python - 提取时间戳在特定范围内的 Python Pandas 记录
- sql - SQL:如何分组并获取两个不同列的最大值
- hana - SAP HANA 智能数据集成
- python - 过滤熊猫中的行
- blazor - 使用 Blazor 将 IJSRuntime 放入站点 _Import.razor 是否安全