Last active
August 3, 2023 23:13
-
-
Save tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e to your computer and use it in GitHub Desktop.
TypeScript friendly assert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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