Created
August 22, 2017 20:11
-
-
Save jcemer/f4bef63864f73307df44d3ddc2383214 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @flow */ | |
import typify from "typify" | |
class Ok<A> { | |
value: A | |
constructor(value: A) { | |
this.value = value | |
} | |
} | |
class Err { | |
msg: string | |
constructor(msg: string) { | |
this.msg = msg | |
} | |
} | |
typify.record("results", { | |
results: "array string", | |
}) | |
type Results = { | |
results: Array<string> | |
} | |
type ResultsResponse = | |
| Ok<Results> | |
| Err | |
function fetchItems() : Promise<Results> { | |
return fetch("/api/items").then((res) => res.json()) | |
} | |
function fetchItemsWithValidation() : Promise<ResultsResponse> { | |
return fetchItems().then((data) => { | |
if (typify.check("results", data)) { | |
return new Ok(data) | |
} | |
return new Err("Invalid JSON") | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good example!