总结TS中常用的运算符

1,459 阅读3分钟

最近在使用ts开发项目,开发中经常有想用某个操作符但是因掌握不熟不知道该用哪个,本文就整理了使用ts在日常开发中常用的运算符和操作符,理解记忆之余便于温故知新

一、 ?.

可选链运算符,对nullundefined可及时停止运算,可解放es5繁琐的判断逻辑,如:

// ts
const val = a?.b

//es5
var val = a === null || a.b

支持的语法如下:

obj?.prop // 尝试访问可能不存在的属性
obj?.[exp] // 同上,计算属性写法
arr?.[index] // 尝试访问可能不存在的索引
func?.[args] // 尝试调用可能不存在的方法

二、!

非空断言运算符,用于断言操作的对象是非null和非undefined类型

  • 从值域中排除nullundefined
function test (params: number | undefined | null, callback: ()=>number | undefined )
{
    const count = params!;// 排除undefined 和null,不报错
    
    const number = callback!() // 除去undefined
}

三、 ?:

可选属性,主要用于类型声明时候对某个属性进行可选标记,这样在实例化时候缺少某个属性就编译器可以不报错

interface Person{
    name : string;
    age : number;
    gender? : string // 可选属性
}

上一篇文章梳理过TS中常见的内置泛型,其中Partial可将属性标记为可选,再来回顾一下

// Partial的源码实现
type Partial<T>={
    [key in  keyof T]? : T[key]
}

?表示可选,那么-?顾名思义表示必选,尤其回顾一下TS中内置泛型Required

type Required<T>={
    [key in keyof T]-? : T[key] 
}

四、??

空值合并运算符,当左侧操作数为null或者undefined时,返回右侧的操作数,否则返回左侧的操作数,与||不同的是,逻辑或会在左侧操作数为falsy时(如:“”,0)返回右侧操作数,此时如果对空字符串或者0有意义时使用空值合并运算符会省去es5中的很多判断

const data1 = 0

// 如果data1是undefined或者null,data2=100
const data2 = data1 ?? 100

// es5实现
const data2 = data1===undefined || data1===null ? 100 : data1

可用于短路,当空值合并运算符的做表达式不是null或者undefined时,不会对右侧表达式进行求职

function A() { console.log('A was called'); return undefined;}
function B() { console.log('B was called'); return false;}
function C() { console.log('C was called'); return "foo";}

console.log(A() ?? C());
console.log(B() ?? C());

五、&

交叉类型运算符,用于将多种类型叠加到一起成为一个新类型

type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };

let point: Point = {
  x: 1,
  y: 1
}

当混入的成员有类型覆盖时,新类型为never

interface X {
  c: string;
  d: string;
}

interface Y {
  c: number;
  e: string
}

type XY = X & Y;
type YX = Y & X;

let p: XY;
let q: YX;

// 生成的新类型
type XY={
    c : never;
    d :string;
    e : string
}

六、|

联合类型运算符,表示取值可以是多种类型中的一种,联合类型常与nullundefined一起使用

const sayHello = (name: string | undefined) => { /* ... */ };

// 参数可以不填
sayHello("semlinker");
sayHello(undefined);

七、_

数字分割符,不会改变字面量的值,用于逻辑分组便于阅读。

const inhabitantsOfMunich = 1_464_301;
const distanceEarthSunInKm = 149_600_000;
const fileSystemPermission = 0b111_111_000;
const bytes = 0b1111_10101011_11110000_00001101;

// 对应的 es5
"use strict";
var inhabitantsOfMunich = 1464301;
var distanceEarthSunInKm = 149600000;
var fileSystemPermission = 504;
var bytes = 262926349;

八、<Type>

类型断言,在编译时起作用。

  • “尖括号”用法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
  • as语法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;

九、#

私有字段,在class中使用

  • 私有字段必须以#开头
  • 每个私有字段名称都唯一地限定于其包含的类
  • 不能在私有字段上使用Typescript可访问性修饰符,如:public或private
  • 私有字段不能在包含的类之外访问,甚至不能被检测到
class Person {
  #name: string;

  constructor(name: string) {
    this.#name = name;
  }

  greet() {
        console.log(`${this.#name}!`);
  }
}

let semlinker = new Person("Semlinker");

至此仍有@装饰器符号使用未梳理,准备另起章节深入剖析