How to check undefined in Typescript

前端 未结 9 980
面向向阳花
面向向阳花 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

    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.

提交回复
热议问题