Skip to content

Commit

Permalink
[flow-enums-runtime] Add definition (#4567)
Browse files Browse the repository at this point in the history
  • Loading branch information
Brianzchen committed Feb 15, 2024
1 parent 388e9ed commit ca06757
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
@@ -0,0 +1,17 @@
declare module 'flow-enums-runtime' {
declare type Members = { +[key: string]: string };

declare type EnumPrototype<T> = {|
isValid: (x: $Keys<T>) => boolean,
cast: <V>(x: V) => V | void,
members: () => Array<$Keys<T>>,
getName: (value: string) => string,
|};

declare type Enum = {|
<T: Members>(members?: T): {| ...EnumPrototype<T>, ...T |},
Mirrored: <T: Members>(members: Array<$Keys<T>>) => {| ...Members, ...EnumPrototype<T> |},
|};

declare module.exports: Enum;
}
@@ -0,0 +1,39 @@
// @flow
import { describe, test } from 'flow-typed-test';
import flowEnumRuntime from 'flow-enums-runtime';

describe('flow-enums-runtime', () => {
test('default function', () => {
const obj = { a: 'a' }

const res = flowEnumRuntime(obj);

res.a;
res.isValid('a');
const valid = res.cast('a');
// $FlowExpectedError[incompatible-use]
valid.toLowerCase();
if (valid) {
valid.toLowerCase();
}
(res.members(): Array<$Keys<typeof obj>>);

// $FlowExpectedError[prop-missing]
res.b;
});

test('Mirrored', () => {
const { Mirrored } = flowEnumRuntime;

const obj = { a: 'b' };

Mirrored<typeof obj>(([]: Array<$Keys<typeof obj>>));
Mirrored<{| a: 'a', b: 'b' |}>(['a', 'b']);
// $FlowExpectedError[prop-missing]
Mirrored<{| a: 'a', b: 'b' |}>(['a', 'b', 'c']);
// $FlowExpectedError[incompatible-call]
Mirrored();
// $FlowExpectedError[incompatible-call]
Mirrored<{| a: 'a', b: 'b' |}>([1]);
});
});

0 comments on commit ca06757

Please sign in to comment.