Skip to content

Instantly share code, notes, and snippets.

@tkrotoff
Last active August 3, 2023 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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.
*
* If your code only runs in Node.js, prefer `import { strict as assert } from 'node:assert'`
* because it throws.
*
* https://gist.github.com/tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e
* https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#assertion-functions
*/
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" for 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