Skip to content

Commit

Permalink
clarify message functionality in readme
Browse files Browse the repository at this point in the history
  • Loading branch information
BirdHighway committed Mar 6, 2024
1 parent 4a02742 commit b9022f7
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ invariant(falsyValue, 'This will throw!');
// Error('Invariant violation: This will throw!');
```

## Error Messages

`tiny-invariant` allows you to pass a single string message. With [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) there is really no need for a custom message formatter to be built into the library. If you need a multi part message you can just do this:

```js
invariant(condition, `Hello, ${name} - how are you today?`);
```

You can also provide a function to generate your message, for when your message is expensive to create

```js
Expand All @@ -29,13 +37,7 @@ import invariant from 'tiny-invariant';
invariant(value, () => getExpensiveMessage());
```

## Why `tiny-invariant`?

The [`library: invariant`](https://www.npmjs.com/package/invariant) supports passing in arguments to the `invariant` function in a sprintf style `(condition, format, a, b, c, d, e, f)`. It has internal logic to execute the sprintf substitutions. The sprintf logic is not removed in production builds. `tiny-invariant` has dropped all of the sprintf logic. `tiny-invariant` allows you to pass a single string message. With [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) there is really no need for a custom message formatter to be built into the library. If you need a multi part message you can just do this:

```js
invariant(condition, `Hello, ${name} - how are you today?`);
```
When `process.env.NODE_ENV` is set to `production`, the message will be replaced with the generic message `Invariant failed`.

## Type narrowing

Expand Down

0 comments on commit b9022f7

Please sign in to comment.