TypeScript - null versus undefined

后端 未结 3 518
挽巷
挽巷 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 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.

提交回复
热议问题