JS Built-ins
TypeScriptintermediate

Type Guard β€” assertNonNull

πŸ“– Usage Example
function assertNonNull<T>(val: T | null | undefined): asserts val is T {
  if (val == null) throw new Error('Unexpected null')
}
assertNonNull(value)  // TypeScript knows value is T after this line

An assertion function with 'asserts val is T' tells TypeScript the value is non-null after the call.

Type Guards: Assertion Functions

TypeScript 3.7 introduced assertion functions β€” functions that throw instead of returning false.
Use the asserts x is T return type to tell TypeScript the value is narrowed after the call.

Challenge: Implement assertNonNull<T>(x: T | null | undefined, msg?: string): asserts x is T.

assertNonNull('hello')   // does nothing (no throw)
assertNonNull(null)      // throws Error
πŸ’‘ Hints (1)
  • β€’ Throw if x === null || x === undefined, otherwise do nothing.