Four Comparison in TypeScript to Understand Basic Types Better

Optional vs. Default value vs. Undefined; Null vs. Undefined; Never vs. Void; Any vs. Unknown

Photo by Raychan on Unsplash

Optional vs. Default value vs. Undefined

1. With optional parameter, the type will be undefined if param omitted:function f1(x?: number) { return x }
// type ======>
// function f1(x?: number | undefined): number | undefined
assert.equal(f1(123), 123);
assert.equal(f1(undefined), undefined);
assert.equal(f1(), undefined);
2. With default parameter, the type value will be the default type if param is omitted, function f2(x = 123) { return x }
// type ======>
// function f2(x?: number): number
assert.equal(f2(123), 123);
assert.equal(f2(undefined), 123);
assert.equal(f2(), 123);
3. With a union type including undefined, the param cannot be omitted:function f3(x: undefined | number) { return x }
// type ======>
// function f1(x?: number | undefined): number | undefined
assert.equal(f3( 123), 123);
assert.equal(f3(undefined), undefined);
f3(); //Expected 1 arguments, but got 0.

Null vs. Undefined

- Undefined means a variable has been declared but not yet assigned var test;
alert(test); // undefined
alert(typeof test); // undefined
- Null is an assignment value. It can be assigned to a variable as a representation of no value. Note that its type is ACTUALLY OBJECT!!!var test = null;
alert(test); // null
alert(typeof test); // object
=================================>null === undefined // false
null == undefined // true
null === null // true

Never vs. Void

let bar: never = (() => { throw new Error(`Throw my hands in the air like I just don't care`) })();
function foo(x: string | number): boolean {
if (typeof x === "string") {
return true;
} else if (typeof x === "number") {
return false;
}
return fail("Unexhaustive!");
}
function fail(message: string): never { throw new Error(message); }
let unusable: void = undefined;
// if` — strictNullChecks` is not given
unusable = null;

Any vs. Unknown

declare function getValue(key: string): any;
const str: string = getValue("myString");
let myVar: unknown;let myVar1: unknown = myVar;   // OK
let myVar2: any = myVar; // OK
let myVar3: boolean = myVar;
// Type 'unknown' is not assignable to type 'boolean'
// The following operations on myVar all give the error:
// Object is of type 'unknown'
myVar[0];
myVar();
myVar.length;
new myVar();
declare const maybe: unknown;
if (maybe === true) {
const aBoolean: boolean = maybe;
const aString: string = maybe;
// Error : Type 'boolean' is not assignable to type 'string'.
}
let looselyTyped: any = 4;
looselyTyped.ifItExists(); // ok
let strictlyTyped: unknown = 4;
strictlyTyped.toFixed();
// ERROR: Object is of type 'unknown'.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store