Skip to content

Instantly share code, notes, and snippets.

@tkrotoff
Last active May 10, 2024 13:43
Show Gist options
  • Save tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e to your computer and use it in GitHub Desktop.
Save tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e to your computer and use it in GitHub Desktop.
TypeScript friendly assert
/**
* Writes an error message to the console if the assertion is false.
*
* If the assertion is true, nothing happens.
* This is similar to React invariant: https://github.com/zertosh/invariant
*
* If your code only runs in Node.js, prefer `import { strict as assert } from 'node:assert'`
* because it throws.
*
* What is an assertion?
* - https://en.wikipedia.org/wiki/Assertion_(software_development)
* - https://en.wikipedia.org/wiki/Design_by_contract
*
* TypeScript assertion signature: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#assertion-functions
*
* https://gist.github.com/tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e
*/
export function assert(_condition: boolean, _message?: string): asserts _condition {
// eslint-disable-next-line no-console, prefer-rest-params
console.assert(...arguments);
}
import { assert } from './assert';
test('TypeScript "asserts condition"', () => {
const foobar = (): number | string => 'foobar';
const str = foobar();
assert(typeof str === 'string');
// Without assert(), TypeScript error: "Property 'includes' does not exist on type 'number'"
str.includes('foo');
});
test('console output', () => {
expect.assertions(4);
const consoleMock = jest.spyOn(console, 'assert').mockImplementation();
assert(false);
// "Unreachable code detected" by TypeScript
expect(consoleMock).toHaveBeenCalledTimes(1);
// Tests that it's not "false, undefined"
expect(consoleMock).toHaveBeenCalledWith(false);
assert(false, 'a message');
expect(consoleMock).toHaveBeenCalledTimes(2);
expect(consoleMock).toHaveBeenCalledWith(false, 'a message');
consoleMock.mockRestore();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment