Non-null assertions

suggest change

The non-null assertion operator, \!, allows you to assert that an expression isn’t null or undefined when the TypeScript compiler can’t infer that automatically:

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;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents