How to check undefined in Typescript

前端 未结 9 957
面向向阳花
面向向阳花 2021-02-04 23:05

I am using this code to check undefined variable but it\'s not working.

9条回答
  •  迷失自我
    2021-02-04 23:59

    From Typescript 3.7 on, you can also use nullish coalescing:

    let x = foo ?? bar();
    

    Which is the equivalent for checking for null or undefined:

    let x = (foo !== null && foo !== undefined) ?
        foo :
        bar();
    

    https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing

    While not exactly the same, you could write your code as:

    var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
    

提交回复
热议问题