Skip to content

Commit c2c846a

Browse files
committed
Add invariant module
If Flow sees a function named `invariant` being called, it will behave as if an exception was thrown inline where the passed condition isn't true. The is useful for determining unreachable code and maintaining refinements. In other words, `invariant(foo, msg)` is equivalent to: if (!foo) throw new Error(msg); in that Flow even refines `foo` as truthy below the condition in both cases.
1 parent 674151c commit c2c846a

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

.eslintrc.yaml

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ globals:
2727
addColonText: readonly
2828
hasOwnProp: readonly
2929
hyphenateTitle: readonly
30+
invariant: readonly
3031
nonEmpty: readonly
3132
l: readonly
3233
ln: readonly

root/utility/invariant.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
* @flow strict
3+
* Copyright (C) 2020 MetaBrainz Foundation
4+
*
5+
* This file is part of MusicBrainz, the open internet music database,
6+
* and is licensed under the GPL version 2, or (at your option) any
7+
* later version: http://www.gnu.org/licenses/gpl-2.0.txt
8+
*/
9+
10+
/*
11+
* If Flow sees a function named `invariant` being called, it will behave
12+
* as if an exception was thrown inline where the passed condition isn't
13+
* true. The is useful for determining unreachable code and maintaining
14+
* refinements.
15+
*/
16+
export default function invariant(
17+
cond: mixed,
18+
msg?: string = 'Invariant Violation',
19+
): void {
20+
// flowlint sketchy-null-mixed:off
21+
if (!cond) {
22+
throw new Error(msg);
23+
}
24+
}

root/vars.js

+3
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,6 @@ declare var texp: {
109109

110110
// https://flow.org/en/docs/tips/switch-statement-exhaustiveness/
111111
declare var exhaustive: (action: empty) => void;
112+
113+
// root/utility/invariant.js
114+
declare var invariant: (cond: mixed, msg?: string) => empty;

webpack/providePluginConfig.js

+2
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,14 @@ const expandPath = path.resolve(i18nPath, 'expand2react');
1818
const expandTextPath = path.resolve(i18nPath, 'expand2text');
1919
const hasOwnPropPath = path.resolve(commonPath, 'utility/hasOwnProp');
2020
const nonEmptyPath = path.resolve(commonPath, 'utility/nonEmpty');
21+
const invariantPath = path.resolve(__dirname, '../root/utility/invariant');
2122

2223
module.exports = {
2324
'addColon': [addColonPath, 'default'],
2425
'addColonText': [addColonPath, 'addColonText'],
2526
'hasOwnProp': [hasOwnPropPath, 'default'],
2627
'hyphenateTitle': [hyphenateTitlePath, 'default'],
28+
'invariant': [invariantPath, 'default'],
2729
'nonEmpty': [nonEmptyPath, 'default'],
2830

2931
'l': [i18nPath, 'l'],

0 commit comments

Comments
 (0)