非空断言
非空断言运算符 !
允许你在 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;
}