Skip to content
GreenSnippets

Assert a value is not null or undefined

An assertion function that narrows away null and undefined and throws a clear error otherwise.

TypeScript
function assertDefined<T>(value: T, message = "Expected value to be defined"): asserts value is NonNullable<T> {
  if (value === null || value === undefined) throw new Error(message);
}

function requireValue<T>(value: T, message?: string): NonNullable<T> {
  assertDefined(value, message);
  return value;
}

Example / expected output

Output
const user = requireValue(users.get(id), `No user ${id}`); // User, never undefined

How it works

Non-null assertions (value!) just silence the compiler. An assertion function narrows the type and fails loudly with a message if the assumption is wrong. Use it at boundaries where the type system cannot know a value is present, such as Map.get or DOM queries.