Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - null versus undefined

Tags:

typescript

The TypeScript Coding Guidelines state

Use undefined. Do not use null

Having just read another article on ECMAScript, which advocates for null over undefined, I was wondering whether Microsoft’s or the TypeScript team’s rationale is known for this decision?

like image 781
Matthew Layton Avatar asked Apr 10 '18 06:04

Matthew Layton


People also ask

Should I use null or undefined in TypeScript?

TypeScript team doesn't use null : TypeScript coding guidelines and it hasn't caused any problems. Douglas Crockford thinks null is a bad idea and we should all just use undefined . However, NodeJS style code bases uses null for Error arguments as standard as it denotes Something is currently unavailable .

Is it better to use undefined or null?

Only use null if you explicitly want to denote the value of a variable as having "no value". As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing".

What is difference between null vs undefined?

Definition: Null: It is the intentional absence of the value. It is one of the primitive values of JavaScript. Undefined: It means the value does not exist in the compiler.


1 Answers

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.

like image 117
Estus Flask Avatar answered Sep 18 '22 21:09

Estus Flask