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
let value: number | null = Math.random() > 0.5 ? 42 : null
assert(value)
let newValue: number = value
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
You might even want to require this, but I personally find it unncessary.
assert(typeof value === "number", "value must be number")