ts中的?、??、!、!!

有时候经常分不清楚ts中的?和!, 今天来详细介绍一下。

下面是?、??、!、!!的基本介绍:

  • 属性或参数中使用?表示该属性或参数为可选项
  • ??表示只有当左侧为null和undefined时, 才会返回右侧的数
  • 属性或参数中使用!表示表示强制解析(告诉typescript编译器,这里一定有值)
  • 变量前使用!表示取反, 变量后使用!表示类型推断排除null、undefined从而使null 和undefined类型可以赋值给其他类型并通过编译
  • !!表示将把表达式强行转换为逻辑值

?相关代码

当使用A对象属性A.B时,如果无法确定A是否为空,则需要用A?.B,表示当A有值的时候才去访问B属性,没有值的时候就不去访问,如果不使用?则会报错

const user = null;
console.log(user.account)   // 报错
console.log(user?.account)  // undefined

另外一种解释:?.允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?.操作符的功能类似于.链式操作符,不同之处在于,在引用为空(null 或者 undefined)的情况下不会引起错误而是直接返回null or undefined

!相关代码

!的示例代码如下:

interface IDemo {
    x?: number 
}

const demo = (parma: IDemo) => {
    const y:number = parma.x!  // 变量值可空, 当x为空时将返回undefined
    return y
}
console.log(demo({}))          // 输出: undefined
console.log(demo({x: 3}))      // 输出: 3

另外||可与!结合使用:

interface IDemo {
    x?: number
}
const parma:IDemo = {};
const parma2:IDemo = {x: 3};
// 如果为undefined,返回y=1,如果不为undefined,则返回parma.x的值
const y:number = parma.x || 1;
console.log(y); // 输出: 1
const z:number = parma2.x || 1;
console.log(z); // 输出: 3

// 上述原理如下:
console.log(null || "xx")       // 输出: xx
console.log(undefined || "xx")  // 输出: xx

??和!!示例代码

console.log(!!(0 + 0)) // 输出: false
console.log(!!(3 * 3)) // 输出: true

const foo = null ?? 'default string';
console.log(foo); // 输出: "default string"

const baz = 0 ?? 42;
console.log(baz); // 输出: 0