Last active
March 26, 2018 13:48
-
-
Save girvo/b4207d4fc92f6b336813d1404309baab to your computer and use it in GitHub Desktop.
Flow type inference using the "decoders" library
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 { guard, object, string, number } from 'decoders' | |
import type { Decoder } from 'decoders' | |
// This is the type-level "function" that pulls the generic out of the decoder | |
type ExtractDecoderType = <T>(d: Decoder<T>) => T | |
// Now we define our run-time decoder, without defining the type first... | |
const person = object({ | |
name: string, | |
age: number | |
}) | |
// And here is the "magic": We extract the inferred type out of the Decoder<T> | |
// using the amazing $Call utility function and the "typeof" type-level operator | |
type Person = $Call<ExtractDecoderType, typeof person> | |
// Now we can make our actual decoder | |
const decodePerson = guard(person) | |
// And here's our test function | |
function hello (p: Person): string { | |
return `Hello, ${p.name}` | |
} | |
// Time to try it out. | |
// | |
// The run-time behaviour now matches the type-level behaviour, yay! | |
const a = decodePerson({ | |
name: 'test', | |
age: 1 | |
}) | |
// Look ma! 100% Flow coverage! | |
console.log(hello(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment