Skip to content

Instantly share code, notes, and snippets.

@lucas-jones
Created May 17, 2020 20:05
Show Gist options
  • Save lucas-jones/90d0f7b54fc89ba4ef573ce2d2f33a71 to your computer and use it in GitHub Desktop.
Save lucas-jones/90d0f7b54fc89ba4ef573ce2d2f33a71 to your computer and use it in GitHub Desktop.
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