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?
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 .
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".
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With