Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e4e019660 | ||
|
|
2bc148342d |
No files matched your search
+20
-18
@@ -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, {});
|
||||
}
|
||||
@@ -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" });
|
||||
}
|
||||
Reference in new issue
Block a user