755 B
755 B
Type Mapping in TypeScript
This example demonstrates how to use TypeScript's mapped types and generics to create a type-safe mapping between an operation code (enum) and the expected arguments for that operation.
type OpArgsMapping = {
[OpCode.PING]: PingEvent;
[OpCode.HELLO]: HelloEvent;
[OpCode.MOVE]: MoveEvent;
};
class WebSocketClient {
public send<TOp extends OpCode, TArgs extends OpArgsMapping[TOp]>(
op: TOp,
args: TArgs,
) {
// ...
}
}
When calling send, TypeScript automatically infers the correct type for args based on the value passed for op.
client.send(OpCode.MOVE, { x: 10, y: 20 }); // Correct
client.send(OpCode.MOVE, { name: "foo" }); // -> 💥 Compiler Error