Created
May 17, 2020 20:05
-
-
Save lucas-jones/90d0f7b54fc89ba4ef573ce2d2f33a71 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
enum Opcodes { | |
NAME_CHANGE = "nameChange", | |
POSITION = "position" | |
} | |
type NameChangePacket = { | |
opcode: Opcodes.NAME_CHANGE, | |
name: string | |
}; | |
type PositionPacket = { | |
opcode: Opcodes.POSITION, | |
x: number, | |
y: number | |
}; | |
type Packets = NameChangePacket | PositionPacket; | |
const packet: Packets = { | |
} as any; | |
type PacketsOfType<T extends Opcodes> = Extract<Packets, { opcode: T }>; | |
const on = <T extends Opcodes>(opcode: T, onPacket: (packet: PacketsOfType<T>) => void) => (packet: Packets) => { | |
if (packet.opcode === opcode) { | |
onPacket(packet as PacketsOfType<T>); | |
} | |
}; | |
on(Opcodes.NAME_CHANGE, (packet) => { | |
console.log(packet.name) | |
}) | |
on(Opcodes.POSITION, (packet) => { | |
console.log(packet.x) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment