Skip to main content

[非空断言操作符]

非空断言操作符会从变量中移除 undefined 和 null,只需在变量后面添加一个 !

Try it

忽略变量的 undefined | null

在变量后面添加一个 ! 就会忽略 undefined 和 null。

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

函数执行时忽略 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
}

注意:这个操作符只有在 strictNullChecks 打开的时候才会有效果。反之,编译器将不会检查 undefined 和 null

React refs 的事件处理

React refs 可以用来访问 HTML 节点 DOM。ref.current 的值有时可能是 null(这是因为引用的元素还没有 mounted)。

在很多情况下,我们能确定 current 元素已经 mounted,因此,null 是不需要的。

在接来下的示例中,当点击按钮时 input 会滚动到可视区域:

const ScrolledInput = () => {
const ref = React.createRef<HTMLInputElement>();

const goToInput = () => ref.current.scrollIntoView(); //compilation error: ref.current is possibly null
const goToInput = () => ref.current!.scrollIntoView(); //all good!

return (
<div>
<input ref={ref}/>
<button onClick={goToInput}>Go to Input</button>
</div>
);
};