|
Last change
on this file was a762898, checked in by istevanoska <ilinastevanoska@…>, 5 months ago |
|
Added visualizations
|
-
Property mode
set to
100644
|
|
File size:
1.8 KB
|
| Line | |
|---|
| 1 | const isProduction: boolean = process.env.NODE_ENV === 'production';
|
|---|
| 2 | const prefix: string = 'Invariant failed';
|
|---|
| 3 |
|
|---|
| 4 | /**
|
|---|
| 5 | * `invariant` is used to [assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) that the `condition` is [truthy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy).
|
|---|
| 6 | *
|
|---|
| 7 | * 💥 `invariant` will `throw` an `Error` if the `condition` is [falsey](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy)
|
|---|
| 8 | *
|
|---|
| 9 | * 🤏 `message`s are not displayed in production environments to help keep bundles small
|
|---|
| 10 | *
|
|---|
| 11 | * @example
|
|---|
| 12 | *
|
|---|
| 13 | * ```ts
|
|---|
| 14 | * const value: Person | null = { name: 'Alex' };
|
|---|
| 15 | * invariant(value, 'Expected value to be a person');
|
|---|
| 16 | * // type of `value`` has been narrowed to `Person`
|
|---|
| 17 | * ```
|
|---|
| 18 | */
|
|---|
| 19 | export default function invariant(
|
|---|
| 20 | condition: any,
|
|---|
| 21 | // Not providing an inline default argument for message as the result is smaller
|
|---|
| 22 | /**
|
|---|
| 23 | * Can provide a string, or a function that returns a string for cases where
|
|---|
| 24 | * the message takes a fair amount of effort to compute
|
|---|
| 25 | */
|
|---|
| 26 | message?: string | (() => string),
|
|---|
| 27 | ): asserts condition {
|
|---|
| 28 | if (condition) {
|
|---|
| 29 | return;
|
|---|
| 30 | }
|
|---|
| 31 | // Condition not passed
|
|---|
| 32 |
|
|---|
| 33 | // In production we strip the message but still throw
|
|---|
| 34 | if (isProduction) {
|
|---|
| 35 | throw new Error(prefix);
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | // When not in production we allow the message to pass through
|
|---|
| 39 | // *This block will be removed in production builds*
|
|---|
| 40 |
|
|---|
| 41 | const provided: string | undefined = typeof message === 'function' ? message() : message;
|
|---|
| 42 |
|
|---|
| 43 | // Options:
|
|---|
| 44 | // 1. message provided: `${prefix}: ${provided}`
|
|---|
| 45 | // 2. message not provided: prefix
|
|---|
| 46 | const value: string = provided ? `${prefix}: ${provided}` : prefix;
|
|---|
| 47 | throw new Error(value);
|
|---|
| 48 | }
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.