In react, if we declare and do not initialise a variable, it would be undefined
var a; //undefined If we would want to assign a variable and initialise a variable later, we could first assign it as null. (Not recommended)
var a = null; As undefined and null is different, we should perform validation whenever we think that the code would break if the variable is null or undefined.
typeof null // "object" (not "null" for legacy reasons) typeof undefined // "undefined" To make the code reusable, we could define a utility function to perform the validation. The function could be as simple as a function that takes in any type of input, or a function that utilise Generics.
function nonNullish(value: unknown): boolean { return value !== (null || undefined) ? true : false; } function assertNonNullish<TValue>(value: TValue): boolean { return value !== (null || undefined) ? true : false; }
Top comments (1)
Hi Wenrei, great post!