UNPKG

1.12 kBPlain TextView Raw
1const isProduction: boolean = process.env.NODE_ENV === 'production';
2const prefix: string = 'Invariant failed';
3
4// Throw an error if the condition fails
5// Strip out error messages for production
6// > Not providing an inline default argument for message as the result is smaller
7export default function invariant(
8 condition: any,
9 // Can provide a string, or a function that returns a string for cases where
10 // the message takes a fair amount of effort to compute
11 message?: string | (() => string),
12): asserts condition {
13 if (condition) {
14 return;
15 }
16 // Condition not passed
17
18 // In production we strip the message but still throw
19 if (isProduction) {
20 throw new Error(prefix);
21 }
22
23 // When not in production we allow the message to pass through
24 // *This block will be removed in production builds*
25
26 const provided: string | undefined =
27 typeof message === 'function' ? message() : message;
28
29 // Options:
30 // 1. message provided: `${prefix}: ${provided}`
31 // 2. message not provided: prefix
32 const value: string = provided ? `${prefix}: ${provided}` : prefix;
33 throw new Error(value);
34}