Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
interface Message<Type extends string | number, Data = never> {
type: Type;
data: Data;
type MessageData<
Msg extends Message<any, any>,
Type extends Msg['type']
> = Extract<Msg, { type: Type }>['data'];
type ClientMessage =
| Message<'ERROR', { message: string }>
| Message<'CONNECT'>
| Message<'RECONNECT', string>
| Message<'OPEN', { server: string; port: number }>;
function sendMessage<Type extends ClientMessage['type']>(
type: Type,
data: MessageData<ClientMessage, Type>,
) {}
function receiveMessage<Type extends ClientMessage['type']>(
type: Type,
listener: (data: MessageData<ClientMessage, Type>) => void,
) {}
sendMessage('ERROR', { message: 'potato' });
receiveMessage('ERROR', x => x.message);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment