Skip to content

Instantly share code, notes, and snippets.

@silesky
Created October 6, 2020 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silesky/ee67b324394448c9a2f905cf21b0406a to your computer and use it in GitHub Desktop.
Save silesky/ee67b324394448c9a2f905cf21b0406a to your computer and use it in GitHub Desktop.
io-ts with promises
import * as t from 'io-ts';
import { PathReporter } from 'io-ts/lib/PathReporter';
import * as tPromise from 'io-ts-promise';
// [io-ts][https://github.com/gcanti/io-ts](https://github.com/gcanti/io-ts)
// [Take control of unexpected data at runtime with TypeScript](https://blog.logrocket.com/using-typescript-to-stop-unexpected-data-from-breaking-your-app/)
const fetchProduct = () => {
return Promise.resolve({
id: '123',
name: '15mg cbd pen',
category: ['vapes'],
location: {}, // error
});
};
// Product is now a "codec" -- a runtime representation of the static type "Product"
const Product = t.type({
id: t.string,
name: t.string,
category: t.array(t.string),
location: t.type({
warehouses: t.array(t.string),
}),
});
// this special t.typeOf operator gives us the vanilla
type Product = t.TypeOf<typeof Product>;
const getProduct = async (): Promise<Product | void> => {
try {
const product = await fetchProduct().then(tPromise.decode(Product));
return product;
} catch (err) {
if (tPromise.isDecodeError(err)) {
console.log('error due to decoding issue');
} else {
console.log('error due to network issue');
}
return;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment