【问题标题】:Type union and intersection when used in conjunction结合使用时键入 union 和 intersection
【发布时间】:2020-04-23 00:53:37
【问题描述】:

我最近开始学习 TypeScript,对类型交集/联合的概念有点困惑。在下面的代码 sn-p 中,我假设编译器应该警告关于缺少参数 z 的错误,但它不会。

interface DataA { x: string, y: string, z: string }
interface DataB { x: string }
interface A { id: string, data: DataA }
interface B { id: string, data: DataB }

type C = A & B
type D = B
type X = C | D

function bar(val: X) {}

bar({
  id: "some id",
  data: {
    x: "some data",    
    y: "some data"
  }
});

【问题讨论】:

  • 你能解释一下为什么你会假设编译器会抱怨缺少z吗?您传递给var 的值是一个有效的B,可以分配给X = B | C。如果有的话,它可能会抱怨额外的y,但properties of non-discriminated unions present in at least one member do not trigger excess property warnings。如果你能解释你的思考过程,我也许可以解释它与编译器所做的不同之处。祝你好运。
  • 我的假设是 x、y 和 z 应该存在或只存在 x。因此,它将对应于 A 或 A&B,但不是介于两者之间。感谢您的链接,它似乎与我的问题直接相关。

标签: typescript typescript-types


【解决方案1】:

type X = C | D = (A & B) | B,由于A & BB的更严格版本,所以X类型的最低要求是B,你的赋值数据满足B的所有必填字段,甚至有与B 相比,y 的附加字段,因此可以分配给X

【讨论】:

    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2020-08-24
    • 2013-11-04
    • 2021-11-09
    相关资源
    最近更新 更多