UNPKG

1.44 kBMarkdownView Raw
1# idx
2
3`idx` is a utility function for traversing properties on objects and arrays.
4
5If an intermediate property is either null or undefined, it is instead returned.
6The purpose of this function is to simplify extracting properties from a chain
7of maybe-typed properties.
8
9## Usage
10
11Consider the following type:
12
13```
14const props: {
15 user: ?{
16 name: string,
17 friends: ?Array<User>,
18 }
19};
20```
21
22Getting to the friends of my first friend would resemble:
23
24```
25props.user &&
26props.user.friends &&
27props.user.friends[0] &&
28props.user.friends[0].friends
29```
30
31Instead, `idx` allows us to safely write:
32
33```
34idx(props, _ => _.user.friends[0].friends)
35```
36
37The second argument must be a function that returns one or more nested member
38expressions. Any other expression has undefined behavior.
39
40## Babel Transform
41
42The `idx` runtime function exists for the purpose of illustrating the expected
43behavior and is not meant to be executed. The `idx` function is used in
44conjunction with a Babel plugin that replaces it with better performing code:
45
46```
47props.user == null ? props.user :
48props.user.friends == null ? props.user.friends :
49props.user.friends[0] == null ? props.user.friends[0] :
50props.user.friends[0].friends
51```
52
53All this machinery exists due to the fact that an existential operator does not
54currently exist in JavaScript.
55
56## License
57
58`idx` is [BSD licensed](./LICENSE). We also provide an additional
59[patent grant](./PATENTS).