Assert a value is not null or undefined
An assertion function that narrows away null and undefined and throws a clear error otherwise.
- TypeScript
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
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
const user = requireValue(users.get(id), `No user ${id}`); // User, never undefinedHow 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.
Related snippets
- JavaScript Tested
Build RFC 9457 problem details error responses
Return consistent, machine-readable API errors using the application/problem+json format.
- TypeScript Tested
Check an object against a type with satisfies
Validate a config object against an interface while keeping its precise literal types.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- TypeScript Tested
Branded types for IDs
Prevent mixing up UserId and OrderId strings by giving each a unique compile-time brand.

