Skip to content

Instantly share code, notes, and snippets.

@jcemer
Created August 22, 2017 20:11
Show Gist options
  • Save jcemer/f4bef63864f73307df44d3ddc2383214 to your computer and use it in GitHub Desktop.
Save jcemer/f4bef63864f73307df44d3ddc2383214 to your computer and use it in GitHub Desktop.
/* @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")
})
}
@phamjonathan
Copy link

Good example!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment