How to check undefined in Typescript

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

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

相关标签:
9条回答
  • 2021-02-04 23:58

    It actually is working, but there is difference between null and undefined. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.

    For more information about the difference between the both of them, see this answer.

    For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2021-02-04 23:59

    Adding this late answer to check for object.propertie that can help in some cases:

    Using a juggling-check, you can test both null and undefined in one hit:

    if (object.property == null) {
    

    If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:

    if (object.property === null) {
    

    Typescript does NOT have a function to check if a variable is defined.

    Update October 2020

    You can now also use the nullish coallesing operator introduced in Typescript.

    let neverNullOrUndefined = someValue ?? anotherValue;
    

    Here, anotherValue will only be returned if someValue is null or undefined.

    0 讨论(0)
提交回复
热议问题