TS &符号和 | 符号的解析

博客主要介绍了TypeScript中&(Intersection Typs)和|(Union Typs)两种类型。&表示既满足A又满足B,若A和B冲突则为无效类型;|表示或者的关系。此外,还给出了一些使用相关类型的提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前我一直理解为 & 是并集(其实是不对的) | 是|| (这个是对的)。

& (Intersection Typs)

Intersection Typs:&是既满足A又满足B 。如果遇到A和B冲突了,那么此类型就属于无效类型。无论变量怎么写ts都会报错。

e.g1 : this is a paradox. cause property can not be string and number, at the same time。so it turn out to be ‘never’

type bbb =  {propA: number} & {propA: string}; => {propA: never}

e.g2 : this is a paradox. a wrong example

type  aaa =  Record<string,never> & {propA: string}; => ❌
const AAA: aaa = { propA: '' };

报错提示如下:
 Type '{ propA: string; }' is not assignable to type 'Record<string, never>'.
    Property 'propA' is incompatible with index signature.
      Type 'string' is not assignable to type 'never'.ts(2322)

| (Union Typs)

这个好理解 就是 或者的关系

tips

Don’t use {} as a type. {} actually means “any non-nullish value”.

  • If you want a type meaning “any object”, you probably want Record<string, unknown> instead.
  • If you want a type meaning “any value”, you probably want unknown instead.
  • If you want a type meaning “empty object”, you probably want Record<string, never> instead.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值