ts 中一些符号含义

5,341 阅读4分钟

?. 非空执行运算符

运行表达式时,?.前面值返回 nullundefined 时停止 ?. 后面的运算,返回 undefined值;有时可以使用 ?. 来取代 && 运算符

说明

  • ?. 只会检测变量是否为 nullundefined
  • && 检测的是 false 类型值,如:0、空字符串、NaN、null、undefined 和 false 等

eg:

// a 为 `undefined` 或 `null` 时,直接返回 `undefied`, 不会运行 `a.b` 表达式
const temp = a?.b

// 替换 && => ?.
a && a.b => a?.b

编译后:

var temp = (a === null || a === undefined) ? undefined : a.b;

! 非空断言运算符

类型检查器无法断定类型时,! 后缀断言运算符可以用于断言操作对象为非null和非undefined,即排除这两种类型的检查。代码编译转化后将去除该断言符。

适用场景:当确定某操作对象一定为非null和非undefined时使用。否则,在编译运行代码是可能会出现不可预料的错误。! 运算符只是为了避开编写代码时 ts 类型检查器的检查警告。

eg:

const a: string | undefined = undefined;
const b: number = a!;
console.log(b); // undefined 

编译后:

var a = undefined;
var b = a;
console.log(b); // undefined 

?? 空值合并运算符

左侧操作数为 nullundefined 时,其返回右侧的操作数,否则返回左侧的操作数

说明

  • ?? 检测符号左侧变量为 nullundefined时候,返回右侧操作数
  • || 检测符号左侧 false 类型值时,返回右侧操作数
  • 未使用括号表明运算符表达式时,不能与 &&|| 操作符共用

eg:

const a = undefined ?? 'orange';
console.log(a); // 'orange'

const b = false ?? 18;
console.log(baz); // 输出:false

true && undefined ?? 'orange'; // raises a SyntaxError
(null || undefined ) ?? 'orange'; // 返回 'orange'

?: 可选属性运算符

定义接口类型中的可选属性,即该接口类型变量中的可选属性非必填

interface Person {
  name: string;
  age: number;
}
// Property 'age' is missing in type '{ age: number; }' but required in type 'Person'.(2741)
const person: Person  = { name: 'chengcheng' }

// ?: 可选属性运算符
interface Person {
  name: string;
  age?: number;
}
const person: Person  = { name: 'chengcheng' }

& 类型合并运算符

用于类型之中的合并。交叉类型:将多个类型合并为一个类型,包含了所需的所有类型的特性

说明

  • 同名基础类型属性的合并, 类型不同属性返回为 never 类型
  • 同名非基础类型属性的合并,类型不同属性返回合并类型

eg:

// 基本类型合并
interface A {
    name: string;
    age: string;
}
interface B {
    name: string;
    age: number;
}

type AB = A & B;
=> 
type AB = {
    name: string;
    // age 类型不可能即为 string 类型又为 number,即为 never 类型
    age: string & number; 
}

// 非基本类型 
interface D { name: string; }
interface E { age: number; }
interface F { male: boolean; }

interface A { x: D; }
interface B { x: E; }
interface C { x: F; }

type ABC = A & B & C;
=> 
type ABC = {
   x: {
        name: string;
        age: number;
        male: boolean;
   }
}

| 类型分隔运算符

用于类型之中的或逻辑运算。 联合类型:表示类型取值可以为多种类型中的一种

type AgeType = stringnumber;

const age: AgeType = '18';
const age: AgeType = 18;

使用联合类型时,我们须尽量让值的当前类型和实际类型相匹配,类型保护 可以帮助我们实现相应功能

四种的方式来实现类型保护

  • in 关键字
interface Person {
    name: string;
    age: number;
}

interface Cat {
    name: string;
    color: string;
}

type  UniteType = Person | Cat;

function (obj: UniteType) {
    if ('age' in obj) {
        console.log('age: ' + obj.age);
    }
    if ('color' in obj) {
        console.log('color: ' + obj.color);
    }
}
  • typeof 关键字
function person(name: string, age: string | number) {
  if (typeof age === "number") {
      return (name + '-' + String(age));;
  }
  if (typeof age === "string") {
      return (name + '-' + age);
  }
  throw new Error(`Expected string or number, got '${age}'.`);
}
  • instanceof 关键字
interface Animal {
    voiceMethod(): string;
}

class Person implements Animal {
    constructor(prevate mutilVoice: string) {}
    voiceMethod() {
        return this.mutilVoice;
    }
}

class Cat implements Animal {
    constructor(prevate singleVoice: string) {}
    voiceMethod() {
        return this.singleVoice;
    }
}

let animal: Animal = new Cat('喵喵');

// animal 是 Cat 类型实例
if (animal instanceof Cat) {
  // 执行相应逻辑代码
}
  • 自定义类型保护的类型谓词(type predicate)
function isNumber(x: any): x is number {
  return typeof x === 'number';
}

function isString(x: any): x is string {
  return typeof x === 'string';
}

_ 数字分隔运算符

数字之间添加 _ 符号不会影响数字的具体值,只能添加在两个数字之间

eg:

const num1 = 1_100_100;
const num2 = 150_100_100;
const num3 = 0b111_000_111;

编译后:

var num1 = 1100000;
var num2 = 150100100;
var num3 = 455;

解析函数不支持数字分隔符

  • Number()
  • parseInt()
  • parseFloat()

eg:

Number('123_456')
NaN
parseInt('123_456')
123
parseFloat('123_456')
123