non-null assertion operator !
前缀表达式
1、忽略 undefined | null
类型
function myFunc(maybeString: string | undefined | null) {
const onlyString: string = maybeString; //compilation error: string | undefined | null is not assignable to string
const ignoreUndefinedAndNull: string = maybeString!; //no problem
}
2、执行方法时忽略 undefined
type NumGenerator = () => number;
function myFunc(numGenerator: NumGenerator | undefined) {
const num1 = numGenerator(); //compilation error: cannot invoke an object which is possibly undefined
const num2 = numGenerator!(); //no problem
}
3、当断言失败,代码实际上执行js,有可能导致一些错误
const a: number | undefined = undefined;
const b: number = a!;
console.log(b); // prints undefined, although b’s type does not include undefined
ype NumGenerator = () => number;
function myFunc(numGenerator: NumGenerator | undefined) {
const num1 = numGenerator!();
}
myFunc(undefined); // runtime error: Uncaught TypeError: numGenerator is not a function
:::warning 只有 strictNullChecks flag 打开时,这个操作符才有用。关闭时,编译器不检查undefined 和 null 类型。 :::