TypeScript - null versus undefined

后端 未结 3 517
挽巷
挽巷 2021-02-08 02:34

The TypeScript Coding Guidelines state

Use undefined. Do not use null

Having just read another article on ECMAScrip

相关标签:
3条回答
  • 2021-02-08 02:57

    I made some research few months ago and I came out with the fact that undefined must be prioritize using tslint rule 'no-null-keyword'.

    I tried to change my codebase and I had some issues. Why? Because I'm using an API that return null for empty fields.

    I struggled because of the tslint triple-equals rule.

    if (returnedData === undefined) // will be false because returnedData is null

    Which let you 2 options:

    1) Add some parameters to your triple-equals rules.

    "triple-equals": [true, "allow-null-check"] and do If (returnedData == null)

    allow-null-check allow "==" for null

    2) Use If (returnedData) instead but it checks if null/undefined/empty string or a zero

    0 讨论(0)
  • 2021-02-08 02:58

    Why use null over undefined?

    In javascripts objects are dynamic without any type information. therefor:

    var person
    person.namme
    

    could either be a misspell or it could be the name property. If you use undefined as null you won't know when debugging if:

    • variable/property is not initialized yet, or
    • you miss typed the property name.

    Therefor null is preferable over undefined, you defer between:

    • forgot to initialize property and
    • wrong property used.

    That said: Typescript is typed. thus the following code:

    var person
    person.namme
    

    would result in a type error at compilation. Thus null in that sense is no longer needed.

    That said, i still prefer null over undefined.

    0 讨论(0)
  • 2021-02-08 03:02

    No rationale is necessary for guidelines, the requirement could be chosen at random in order to keep the code base consistent.

    As for this guideline, undefined takes more characters to type but doesn't need to be explicitly assigned to nullable variable or property:

    class Foo {
      bar: number|undefined;
    }
    
    function foo(bar: number|undefined) {}
    

    vs.

    class Foo {
      bar: number|null = null;
    }
    
    function foo(bar: number|null = null) {}
    

    Also, it's less convenient to check the type of null value at runtime because typeof val === 'object' for both null and object value, while it's typeof val === 'undefined' for undefined.

    There is relevant TSLint rule that addresses this concern, no-null-keyword.

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