UNPKG

variant-type

Version:

A Variant is a data structure that can be used to represent any other data type.

38 lines (28 loc) 923 B
# variant-type A Variant is a data structure ([tagged union](https://en.wikipedia.org/wiki/Tagged_union)) that can be used to represent any other data type. You define the various potential types and the variant can only represent one of those types at any one time. A good use for this, is representing parts of your React/Redux app state. ```javascript const Any = () => true const Request = Variant({ Unloaded: [], Loading: [], Loaded: [Any], Failed: [Error] }) // ... componentDidMount () { setState({request: Request.Loading}) fetchSomething .then((results) => setState({request: Request.Loaded(results)})) .catch(e => setState({request: Request.Failed(e)})) } // ... render () { return Request.case({ Unloaded: () => 'Nothing to see here.', Loading: () => 'Please be patient.', Loaded: (data) => `Got this data: ${data}`, Failed: (error) => `Sorry: ${error}` }) } ```