Typescript的联合类型和交叉类型

联合类型

在 TypeScript 中,可以使用联合类型来定义对象接口,从而表示一个对象可以具有多种不同结构的类型。联合类型是或的关系!!!

interface Circle {
    kind: "circle";
    radius: number;
}

interface Square {
    kind: "square";
    sideLength: number;
}

type Shape = Circle | Square;

const circle: Shape = { kind: "circle", radius: 5 };
const square: Shape = { kind: "square", sideLength: 4 };

如果如下方错误写法,为什么会报错呢?

const circle: Shape = { kind: "circle", radius: 5 , sideLength: 4};
circle.kind// 可以访问
circle.radius// 会报错
circle.sideLength // 会报错

circle.kind// 可以访问
circle.radius// 会报错
circle.sideLength // 会报错

在 TypeScript 中,当使用联合类型时,一个对象只能包含联合类型中共有的属性。在你的示例中,Circle接口有属性 kind和 radius,而 Square 接口有属性 kind和 sideLength 。

因此,当你将它们组合成联合类型 Shape时,对象只能是{
    kind: "circle";
    radius: number;
},或者{
    kind: "square";
    sideLength: number;
}。

在这种情况下,circle对象可以包含 kind 属性,但它不能同时包含 radius 和 sideLength 属性。因此,当你尝试访问 circle.radius 时会报错,因为 radius 属性并不属于 circle对象。

如果你希望创建一个对象同时包含 kind、radius 和sideLength 属性,你需要使用交叉类型(&)而不是联合类型(|)。

交叉类型

在 TypeScript 中,使用交叉类型创建新类型时,对象必须包含交叉类型中所有属性

交叉类型&是与的关系是并集!!!

interface Animal {
    name: string;
}

interface Mammal {
    hasFur: boolean;
    numberOfLegs: number;
}

// 使用交叉类型组合 Animal 和 Mammal 接口
type MammalAnimal = Animal & Mammal;

const dog: MammalAnimal = {
    name: "Dog",
    hasFur: true,
    numberOfLegs: 4
};

console.log(dog);

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yusirxiaer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值