非空斷言
非空斷言運算子 !
允許你在 TypeScript 編譯器無法自動推斷時斷言表示式不是 null
或 undefined
:
type ListNode = { data: number; next?: ListNode; };
function addNext(node: ListNode) {
if (node.next === undefined) {
node.next = {data: 0};
}
}
function setNextValue(node: ListNode, value: number) {
addNext(node);
// Even though we know `node.next` is defined because we just called `addNext`,
// TypeScript isn't able to infer this in the line of code below:
// node.next.data = value;
// So, we can use the non-null assertion operator, !,
// to assert that node.next isn't undefined and silence the compiler warning
node.next!.data = value;
}