How do you use functions for type protection in TypeScript?

type Node = {
    value: Value;
    next: Node
} | null;

function output(n: Node) {
    function isEmpty() {
        return n === null;
    }
    //  n === null 
    if (isEmpty()) {
        console.log("empty");
    } else {
        // nnull
        n.next = {value: "yo", next: null};
    }
}

this is just a simple example, but most of the time we write a lot of logic in isEmpty , but these logic usually avoid n = null , so the language in else should pass. How to change this?

Nov.19,2021

function isEmpty(n: Node): n is null {
        return n === null;
    }
    //  n === null 
    if (isEmpty(n)) {
        console.log('empty');
    }
Menu