Skip to content

Instantly share code, notes, and snippets.

@tlaitinen
Created August 1, 2018 11:30
Show Gist options
  • Save tlaitinen/885982aef4602e8154b3e35b70ea68cc to your computer and use it in GitHub Desktop.
Save tlaitinen/885982aef4602e8154b3e35b70ea68cc to your computer and use it in GitHub Desktop.
import * as t from 'io-ts';
function request<P extends t.Props>(type:string, props:P) {
return t.type({
type: t.literal(type),
props: t.type(props)
});
}
export const RequestT = t.union([
request('foo', {
baz: t.string,
quux: t.array(t.string)
}),
request('bar', {
a: t.number,
b: t.string
})
]);
export type Request = t.TypeOf<typeof RequestT>;
function f(r:Request) {
switch(r.type) {
case 'foo':
console.log(r.props.baz);
}
}
/*
test.ts:22:27 - error TS2339: Property 'baz' does not exist on type 'TypeOfProps<{ baz: StringType; quux: ArrayType<StringType, string[], string[], mixed>; }> | TypeO...'.
Property 'baz' does not exist on type 'TypeOfProps<{ a: NumberType; b: StringType; }>'.
22 console.log(r.props.baz);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment