Compare commits

...
2 Commits
Author SHA1 Message Date
zekro 9e4e019660 add more typescript examples 2026-07-17 10:52:41 +02:00
zekro 2bc148342d Dwip 2026-07-17 10:28:20 +02:00
3 changed files with 51 additions and 18 deletions

No files matched your search

+20 -18
View File
@@ -1,34 +1,36 @@
enum OpCode {
PING,
HELLO,
MOVE,
PING,
HELLO,
MOVE,
}
type PingEvent = Record<string, never>;
type HelloEvent = {
name: string;
name: string;
};
type MoveEvent = {
x: number;
y: number;
x: number;
y: number;
};
type OpArgsMapping = {
[OpCode.PING]: null;
[OpCode.HELLO]: HelloEvent;
[OpCode.MOVE]: MoveEvent;
[OpCode.PING]: PingEvent;
[OpCode.HELLO]: HelloEvent;
[OpCode.MOVE]: MoveEvent;
};
class WebSocketClient {
public op<TOp extends OpCode, TArgs extends OpArgsMapping[TOp]>(
op: TOp,
args: TArgs,
) {
// ...
}
public op<TOp extends OpCode, TArgs extends OpArgsMapping[TOp]>(
op: TOp,
args: TArgs,
) {
// ...
}
}
function main() {
const client = new WebSocketClient();
client.op(OpCode.HELLO, { name: "foo" });
function main_ws() {
const client = new WebSocketClient();
client.op(OpCode.PING, {});
}
+23
View File
@@ -0,0 +1,23 @@
type ParseUrlParamsRaw<Url> = Url extends `${infer Start}/${infer Rest}`
? ParseUrlParamsRaw<Start> & ParseUrlParamsRaw<Rest>
: Url extends `{${infer Param}}`
? { [P in Param]: string }
: {};
// ParseUrlParamsRaw allows passing objects with any keys (i.e. `{name: "foo"}`) even though
// an empty object is expected (`{}`). This type constraint enforces this by checking if
// the result of ParseUrlParamsRaw<Url> is `{}`. `keyof {}` evaluates to `never`, so
// when `{}` is evaluated an empty Record is expected, otherwise the result of
// ParseUrlParamsRaw is expected.
type ParseUrlParams<Url> = keyof ParseUrlParamsRaw<Url> extends never
? Record<string, never>
: ParseUrlParamsRaw<Url>;
function navigate<P extends string>(path: P, params: ParseUrlParams<P>) {
// ...
}
function main() {
navigate("/hello", {});
navigate("/hello/{name}", { name: "foo" });
}
+8
View File
@@ -0,0 +1,8 @@
# Type Level Programming
## Sources
- https://www.emoses.org/posts/resolver-resolved-pattern/
- https://farazdagi.com/posts/2024-04-07-typestate-pattern/
- https://youtu.be/_ccDqRTx-JU
- https://type-level-typescript.com/