TypeScript中常见的操作符运算符总结


一、非空断言操作符(!)

当我们⽆法断定类型时,可以使用后缀表达式操作符 来断⾔操作对象是⾮ null 或⾮ undefined 类型。

具体来说,比如表达式: x ! , 结果将从 x 值域中排除 null 和 undefined。


(1)、赋值时忽略 null 和 undefined

function test(name: string | undefined | null) {
    
    
  
  // Type 'string | null | undefined' is not assignable to type 'string'.
  // Type 'undefined' is not assignable to type 'string'. 
  const onlyStringName: string = name;   // error
  const ignoreUndefinedAndNullName: string = name!; // Ok
}

(2)、函数调用时忽略 null 和 undefined

type CallBackString = () => string;
function test(call: CallBackString |null| undefined) {
    
    
  // Object is possibly 'undefined'.
  // Cannot invoke an object which is possibly 'undefined'.
  const onlyStringName = call(); // Error
  const ignoreUndefinedAndNullName = call!(); //OK
}

二、可选链操作符(?.)

?. 操作符功能和 . 链式操作符相似,区别在于,在引用为空 (null 或者 undefined) 的情况下不会引起错误,如果给定值不存在,则直接返回 undefined


例如:

const obj = {
    
    
  project: {
    
    
    dir: {
    
    
      file: "name",
    },
  },
};

const file = obj?.project?.dir?.file; // name
const test = obj?.other?.dir; // undefined

三、空值合并运算符(??)与 逻辑或运算符( || )

当左侧操作数为nullundefined ,返回右侧的操作数,否则返回左侧的操作数。

空值合并运算符与逻辑或 || 运算符不同,逻辑或会在左操作数为false 值时返回右侧操作数。


例如:

const file = null ?? 'dir'; // dir
const num = 0 ?? 20;        // 0
const num1 = 0 || 20;			  // 20

四、可选属性运算符(?:)

使⽤ interface 关键字可以声明⼀个接⼝:

interface Student {
    
    
    name: string;
    age: number;
    gender:number;
}

此时定义接口,若是缺少参数将会报错:

let student: Student = {
    name: "name1"
    age:12
}; //Error 

此时使用可选属性,再定义就OK:

interface Student {
    
    
    name: string;
    age: number;
    gender?:number;
}

let student: Student = {
    
    
    name: "name1"
    age:12
}; //ok 

五、运算符(&)

通过 & 运算符可以将多种类型叠加到⼀起合并为⼀个类型。

如下:

type Pointx = {
    
     x: number; };
type Ponity = {
    
     y: number; };

type Point = Pointx & Ponity;
let  point: Point = {
    
     x: 1,  y: 1 }


六、运算符(|)

TypeScript 中,联合类型表示取值可以为多种类型中的⼀种,联合类型通常与 null 或 undefined ⼀起使⽤。

运算符(|)常用在声明联合类型时,分隔每个类型。

const fun = (info:string | null | undefined) => {
    
    }

七、数字分隔符(_)

可以通过下划线作为分隔符来分组数字。

const number1 = 1234_5678
// 等价
const number2 = 12345678;

猜你喜欢

转载自blog.csdn.net/lizhong2008/article/details/133237058