【TypeSctipt】 运算符

本文介绍了JavaScript中新增的非空断言操作符、可选链操作符、空值合并运算符、可选属性运算符以及运算符如&和|的使用,展示了如何处理null和undefined值,以及数字分隔符在数值表示中的应用。
摘要由CSDN通过智能技术生成

1. 非空断言操作符(!)

// 赋值时忽略 null 和 undefined
function test(name: string | undefined | null) {
  // undefined null 不能分配给 string 类型
  const onlyStringName: string = name // error
  const ignoreUndefinedAndNullName: string = name! // Ok
}

// 函数调用时忽略 null 和 undefined
type CallbackString = () => string
function test(call: CallbackString | null | undefined) {
  // undefined null 不能作为函数调用
  const onlyStringName = call() // Error
  const ignoreUndefinedAndNullName = call!() //OK
}

2. 可选链操作符(?.)

// 在引用为空 (null 或者 undefined) 时不会引起错误
const test = obj?.other?.dir // 引用为空时返回 undefined

3. 空值合并运算符(??)与 逻辑或运算符( || )

// ?? 是在左侧判断结果为null 或 undefined时 返回右侧
const file = null ?? 'dir' // dir
const num = 0 ?? 20 // 0
const num1 = 0 || 20 // 20

4. 可选属性运算符(?:)

interface Student {
  name: string
  age: number
  gender?: number // 属性可有可没有
}

5. 运算符(&)

//  可以将多种类型叠加到⼀起合并为⼀个类型
type Pointx = { x: number }
type Ponity = { y: number }
type Point = Pointx & Ponity
let point: Point = { x: 1, y: 1 }

6. 运算符(|)

// 取值可以为多种类型中的⼀种
const fun = (info: string | null | undefined) => {}

7. 数字分隔符(_

// 作为分隔符来分组数字
const number1 = 1234_5678
// 等价于
const number1 = 12345678
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值