Skip to content

Instantly share code, notes, and snippets.

@jamiebuilds
Last active July 19, 2022 19:46
Show Gist options
  • Save jamiebuilds/2a40f565cba317a80bed1eec127340f6 to your computer and use it in GitHub Desktop.
Save jamiebuilds/2a40f565cba317a80bed1eec127340f6 to your computer and use it in GitHub Desktop.

assert() (sometimes called invariant())

Instead of checks like:

if (value === null) {
  throw new Error("missing value")
}
doSomethingThatNeedsValue(value)

Or even worse, checks that silently do nothing:

if (value === null) {
  return
}
doSomethingThatNeedsValue(value)

I use a function called assert()

assert(value)
doSomethingThatNeedsValue(value)

JavaScript implementation:

function assert(value, message) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message || "Assertion failed")
  }
}

Or in TypeScript:

function assert(value: boolean, message?: string): asserts value;
function assert<T>(value: T | null | undefined, message?: string): asserts value is T;
function assert(value: any, message?: string) {
  if (value === false || value === null || typeof value === "undefined") {
    throw new Error(message || "Assertion failed")
  }
}

This makes use of an advanced TypeScript feature asserts which makes it so TypeScript understands your assertions

Assert a value is not null or undefined or false

let value: number | null = Math.random() > 0.5 ? 42 : null
assert(value)
let newValue: number = value

Assert a condition

Any expression that resolves to true or false can also work:

let value: number | null = Math.random() > 0.5 ? 42 : null
assert(typeof value === "number")
let newValue: number = value

Optionally: Provide a message

You might even want to require this, but I personally find it unncessary.

assert(typeof value === "number", "value must be number")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment