Skip to content

Instantly share code, notes, and snippets.

@karlhorky
Created August 21, 2018 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karlhorky/19b883f577764bc2af6d063efb277d0e to your computer and use it in GitHub Desktop.
Save karlhorky/19b883f577764bc2af6d063efb277d0e to your computer and use it in GitHub Desktop.
Flow: Pick utility function to return a subset of keys of an object type
// Source: https://github.com/facebook/flow/issues/3367#issuecomment-414490844
// Flow Try: https://flow.org/try/#0C4TwDgpgBACglgYwNYB4DyAnOBzOA7ALijQCMArCBYAGigGkIQBnI0iqgPigF4oASNgFkAhmDgoAUFHqMm1KVBQMQHABRIiygJQ8ufAKIAbCAFsIeYABVwEdFlx5ayjhI4BuCRNCQolgAw8sIioAN5IfkQkAPZRxsJ4AL60YRFQ8SAJ7grSEghReEzAUAip-oEpRMAYAK4QCW5QAPSNUHhRUBAYGFEYnnkFRQgAjERlvBVQQ371TS2d3RhAA
// I've just came across with the need of defining an object type
// using a subset of another, or in other words, use some props
// definition of a certain object type and intersect this result
// (a reduced object type) with another set of props definitions
// to define a new type.
// I used to do this a lot with PropTypes using pick utility from
// lodash, but we've recently moved to flow and I really miss
// this functionality, so I was wondering if you have ever
// thought of the possibility of adding a $Pick utility type to
// be able to do something like the following.
// I finally came up with a solution 🎉:
type Pick<Origin: Object, Keys: Object> = $ObjMapi<
Keys,
<Key>(k: Key) => $ElementType<Origin, Key>
>;
type T0 = Pick<{k0: boolean}, {k0: any}>;
const c0: T0 = {k0: true}; // no error
const c1: T0 = {k0: 10}; // error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment