add more documentation

This commit is contained in:
zekro committed 2026-07-27 11:32:15 +02:00
1 parent dcef2470cb
commit b86c9d915e
8 files changed
+129 -1

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
# 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.
```typescript
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`.
```typescript
client.send(OpCode.MOVE, { x: 10, y: 20 }); // Correct
client.send(OpCode.MOVE, { name: "foo" }); // -> 💥 Compiler Error
```