跳到主要内容

TS 非空断言操作符、可选链运算符、空值合并运算符

非空断言操作符

https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#non-null-assertion-operator

作用:排除掉变量中的 nullundefeind

使用:a!

示例:

function simpleExample(a: number | undefined) {
const b: number = a; // COMPILATION ERROR: undefined is not assignable to number.
const c: number = a!; // OK
}

可选链运算符

作用:如果遇到 nullundefined 就可以立即停止某些表达式的运行

使用:a?.b

示例:

if(a && a.b) { } 

if(a?.b){ }

空值合并运算符

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html

作用:当左侧操作数为 nullunderined 时,其返回右侧的操作数,否则返回左侧的操作数

使用:a ?? b

示例:

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

const baz = 0 ?? 42;
console.log(baz);
// Expected output: 0

参考