GitXplorerGitXplorer
j

asser-ts

public
3 stars
0 forks
0 issues

Commits

List of commits on branch main.
Verified
09850516624aa966ca66713bf9afafc8c55081b8

Update README.md

jjossmac committed 3 years ago
Unverified
1cb9a09e96040e26e345af6df56e10fb21483297

update readme

jjossmac committed 3 years ago
Unverified
af1db1e6cea27e8264cccacebf4ed3dbdc345cb7

init project

jjossmac committed 3 years ago
Verified
255bcee1fb71859eb40856ef5b60e05c1b1a1975

Initial commit

jjossmac committed 3 years ago

README

The README file for this repository.

Superseded by Emery.

asser-ts

An assertion declares that a condition be true before executing subsequent code.

  • If the condition resolves to true the code continues running.
  • If the condition resolves to false an error will be thrown.

Exports

assert()

Asserts that a condition is true, ensuring that whatever condition is being checked must be true for the remainder of the containing scope.

Note: The narrow type of boolean is an intentional design decision.

function assert(condition: boolean, message?: string): asserts condition;

Other assertion functions may accept "truthy" and "falsy" conditions, while assert only accepts conditions that resolve to boolean.

The goal is to promote consideration from consumers when dealing with potentially ambiguous values like 0 or '', which can introduce subtle bugs.

Messages

The assert function has a default message:

let falsyValue = '';
assert(typeof falsyValue === 'string' && falsyValue.length > 0);
// → TypeError: Assert failed

Or you can provide a custom message:

let falsyValue = -1;
assert(falsyValue >= 0, `Expected a non-negative number, but received: ${falsyValue}`);
// → TypeError: Expected a non-negative number, but received: -1

assertNever()

Asserts that allegedly unreachable code has been executed.

function assertNever(condition: never): never;

Use assertNever to catch logic forks that shouldn't be possible.

function doThing(type: 'draft' | 'published') {
  switch (type) {
    case 'draft':
      return; /*...*/
    case 'published':
      return; /*...*/

    default:
      assertNever(type);
  }
}

Warning: Regardless of the condition, this function always throws.

doThing('archived');
// → Error: Unexpected call to assertNever: 'archived'

Debugging

In development both assert and assertNever will include a debugger statement, which will pause execution to aid debugging.