https://github.com/threepointone/proposal-error-assert
Error.assert() proposal for ECMAScript
https://github.com/threepointone/proposal-error-assert
Last synced: about 1 month ago
JSON representation
Error.assert() proposal for ECMAScript
- Host: GitHub
- URL: https://github.com/threepointone/proposal-error-assert
- Owner: threepointone
- License: mit
- Created: 2023-02-19T11:57:36.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-02-19T11:57:38.000Z (over 2 years ago)
- Last Synced: 2025-03-25T09:11:15.280Z (about 2 months ago)
- Language: TypeScript
- Size: 2.93 KB
- Stars: 11
- Watchers: 3
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## `Error.assert(condition, message)`
Proposal for an `Error.assert()` method.
Author:
- [@threepointone](https://github.com/threepointone) (Sunil Pai, PartyKit)
## Motivation:
Today, it is very common to write a utility function like this:
```js
function assert(condition, message) {
if (condition === false || condition == null) {
throw new Error(
message != null ? `Assertion failed: ${message}` : `Assertion failed`
);
}
}
```And use it it like so:
```js
function add(a, b) {
assert(typeof a === "number", "a must be a number");
assert(typeof b === "number", "b must be a number");
return a + b;
}
```Additionally, this is useful in a typed language like typescript, where you can use it to assert type invariants and narrow the type of a variable:
```ts
function assert(value: boolean, message?: string): asserts value;
function assert(
value: T | null | undefined,
message?: string
): asserts value is T;
function assert(value: unknown, message?: string): void {
if (value === false || value == null) {
throw new Error(
message != null ? `Assertion failed: ${message}` : "Assertion failed"
);
}
}function add(a: number | void, b: number | void): number {
assert(typeof a === "number", "a must be a number");
assert(typeof b === "number", "b must be a number");
return a + b; // a and b are now narrowed to number
}
```There are a number of existing libraries that provide this functionality:
- [assert](https://www.npmjs.com/package/assert)
- [tiny-invariant](https://www.npmjs.com/package/tiny-invariant)
- [invariant](https://www.npmjs.com/package/invariant)
- Runtimes like node.js provide it as part of their standard library (as the `assert` module).This proposal removes the userland implementation, and replaces it with a built-in method, `Error.assert()`.