Skip to content

Instantly share code, notes, and snippets.

@guillaumewuip
Last active July 1, 2020 20:07
Show Gist options
  • Save guillaumewuip/e825aa90a648e8f11b912421b9ddaf16 to your computer and use it in GitHub Desktop.
Save guillaumewuip/e825aa90a648e8f11b912421b9ddaf16 to your computer and use it in GitHub Desktop.
import * as Union from ‘@iadvize-oss/opaque-union;
type $Text = {
text: string;
}
type $Image = {
url: string;
description: string;
}
const MessageUnion = Union.of({
Text: Union.type<$Text>(),
Image: Union.type<$Image>(),
});
// opaque types
export type Text = ReturnType<typeof MessageUnion.of.Text>;
export type Image = ReturnType<typeof MessageUnion.of.Image>;
// union of opaque types
export type Message = Union.Type<typeof MessageUnion>;
// constructors
export const createText = MessageUnion.of.Text;
export const createImage = MessageUnion.of.Image;
// queries
export const text = MessageUnion.Text.lensFromProp(‘text’).get;
export const url = MessageUnion.Image.lensFromProp(‘url’).get;
export const description = MessageUnion.Image.lensFromProp(‘description’).get;
export const isText = MessageUnion.is.Text;
export const isImage = MessageUnion.is.Image;
// transformations
export const addSignature = (signature: string) => MessageUnion.Text.iso.modify(
($text) => ({ ...$text, text: `${$text.text} - ${signature}` })
);
export const withBitlyUrl = MessageUnion.Image.lensFromProp(‘url’)
.modify(convertToBitly);
// fold function from @iadvize-oss/foldable-helpers
const fold = MessageUnion.fold;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment