Last active
October 30, 2020 09:17
-
-
Save amatiasq/669364c14e6fc5db0f766c68128a8f39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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