Code snippet to throw an error for Null or Undefined

Akshay Jain
1 min readJul 13, 2020

I am writing this code snippet that should be helpful to you as a utility function.
It will throw an exact error for you when you want to assert, that something should not be null or undefined

export const shouldNotBeNull = (container: any) => {const entries = Object.entries(container);let error = '';const getErrorMessage = (variable: string, token: string) =>`${variable} should not be ${token}`;const addError = (errorString: string) => (error += errorString);for (let i = 0; i < entries.length; i++) {let [key, value] = entries[i];if (value === null) {addError(getErrorMessage(key, 'null'));}if (value === undefined) {addError(getErrorMessage(key, 'undefined'));}}if (error.length > 0) {throw new Error(error);}};

link to gist
Thank you!

--

--