Skip to content

Instantly share code, notes, and snippets.

@lebedev
Created January 24, 2019 23:50
Show Gist options
  • Save lebedev/60cd207a5985df62c943883aed27e499 to your computer and use it in GitHub Desktop.
Save lebedev/60cd207a5985df62c943883aed27e499 to your computer and use it in GitHub Desktop.
Flow assertions that an object has all properties from enum and no more, compare enums assertions.
// @flow
type enum = 'a' | 'b' | 'c';
type enumSame = 'a' | 'b' | 'c';
type enumSubtype = 'a' | 'b';
type enumDifferent = 'a' | 'b' | 'd';
// Compare enum and enumSame in both directions. No errors.
((('any': any): enum): enumSame);
((('any': any): enumSame): enum);
// Compare enum and enumSubtype in both directions.
// $ExpectError because enum contains elements that enumSubtype doesn't have.
((('any': any): enum): enumSubtype);
((('any': any): enumSubtype): enum);
// Compare enum and enumDifferent in both directions.
// $ExpectError because enum contains elements that enumDifferent doesn't have.
((('any': any): enum): enumDifferent);
// $ExpectError because enumDifferent contains elements that enum doesn't have.
((('any': any): enumDifferent): enum);
// @flow
type AllowedKeys = 'a' | 'b' | 'c';
type ExpectedObjectType = { [AllowedKeys]: any };
type ActualObjectType<T> = { [$Keys<T>]: any };
const GoodObject = { a: 1, b: 2, c: 3 };
((GoodObject: ExpectedObjectType): ActualObjectType<typeof GoodObject>);
const ObjectWithDisallowedKey = { a: 1, b: 2, c: 3, d: 4 };
// $ExpectError because property 'd' is disallowed.
((ObjectWithDisallowedKey: ExpectedObjectType): ActualObjectType<typeof ObjectWithDisallowedKey>);
const ObjectWithMissingKey = { a: 1, b: 2 };
// $ExpectError because property 'c' is missing.
((ObjectWithMissingKey: ExpectedObjectType): ActualObjectType<typeof ObjectWithMissingKey>);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment