【问题标题】:TypeScript – value of a union of object arrays produces intersection, not unionTypeScript – 对象数组联合的值产生交集,而不是联合
【发布时间】:2021-04-12 18:03:37
【问题描述】:

有两个不同对象的数组(数组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 }

另请参阅link to TypeScript playground

我想知道:

  1. 派生类型{ one: string } 是否正确?
  2. 为什么不是{ one: string } | { one: string, two: string }
  3. 有没有办法为任意对象数组实现expected 类型?

谢谢!

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的,派生类型是正确的,但通常不是预期的。

    这就是联合在 TS 中的工作方式。

    考虑下一个例子:

    type a = { one: string };
    type b = { one: string, two: string };
    
    type ab = keyof (a | b); // "one"
    

    TS 将返回 one,因为此密钥可在两种类型(a、b)之间共享。

    为了达到想要的行为,你可以试试distributive conditional types

    当条件类型作用于泛型类型时,它们在给定联合类型时变得可分配

    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 }
    
    

    Playground

    【讨论】:

    • 太棒了,谢谢!在这种情况下,TS 行为感觉非常不直观。
    • 这里catchts.com你可以找到一些有趣的类型
    猜你喜欢
    • 2021-08-13
    • 2018-11-13
    • 2015-06-01
    • 2018-05-11
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多