Skip to content

Instantly share code, notes, and snippets.

@guillaumewuip
guillaumewuip / Message.ts
Created February 20, 2020 07:58
How to model your entities - 10
import { TextMessage, ImageMessage, AudioMessage, fold } from ‘./Message’;
const renderMessage = fold(
(textMessage: TextMessage) => <TextComponent text={message.text} />),
(imageMessage: ImageMessage) => <ImageComponent url={message.url} description={message.description} />,
(audioMessage: AudioMessage) => <AudioComponent url={message.url} description={message.description} />
)
// Somewhere in a component far, far away...
return (
@guillaumewuip
guillaumewuip / Message.ts
Last active February 20, 2020 08:13
How to model your entities - 11
import { createFold } from ‘@iadvize-oss/foldable-helpers’;
// fold :: (TextMessage -> R) -> (ImageMessage -> R) -> (AudioMessage -> R) -> Message -> R
// “feeding” the fold-creator with our previously created type guards
const fold = createFold(isText, isImage, isAudio);
// or, passing function with an object to give them names
import { createFoldObject } from ‘@iadvize-oss/foldable-helpers’;
@guillaumewuip
guillaumewuip / Message.ts
Last active February 26, 2020 06:56
How to model your entities - 12
createText(text: string): TextMessage
text(message: TextMessage): string
createImage(url: string, description: string): ImageMessage
createAudio(url: string, description: string): AudioMessage
url(message: ImageMessage | AudioMessage): string,
toText(message: ImageMessage): TextMessage
...
@guillaumewuip
guillaumewuip / Message.ts
Last active February 20, 2020 16:55
How to model your entities - 13
export type $TextMessage = {
text: string;
}
const { toOpaque, fromOpaque, isOpaque } = createOpaqueAPI<
'TextMessage',
$TextMessage,
>('TextMessage’);
export type TextMessage = ReturnType<typeof toOpaque>;
@guillaumewuip
guillaumewuip / Example.ts
Created February 20, 2020 08:04
How to model your entities - 14
import {
createText,
createImage,
createAudio,
AudioMessage,
description,
url,
fold,
} from ‘fabulous-Message-library’;
// message.ts
import { createOpaqueAPI } from ‘@iadvize-oss/opaque-type’;
import { createFoldObject } from ‘@iadvize-oss/foldable-helpers’;
type $Text = {
text: string;
}
type $Image = {
url: string;
import * as Union from ‘@iadvize-oss/opaque-union;
type $Text = {
text: string;
}
type $Image = {
url: string;
description: string;
}
type $Text = {
text: string;
};
type $Image = {
url: string;
description: string;
};
const MessageUnion = Union.of({
export const createText = MessageUnion.of.Text;
export const createImage = MessageUnion.of.Image;
export type Text = ReturnType<typeof MessageUnion.of.Text>;
export type Image = ReturnType<typeof MessageUnion.of.Image>;
export function createEmptyText() {
return MessageUnion.of.Text({ text: ‘’ }); // you must pass a $Text here
}