add more typescript examples
This commit is contained in:
1 parent
2bc148342d
commit
9e4e019660
2 files changed
+16
-4
No files matched your search
@@ -4,6 +4,8 @@ enum OpCode {
|
||||
MOVE,
|
||||
}
|
||||
|
||||
type PingEvent = Record<string, never>;
|
||||
|
||||
type HelloEvent = {
|
||||
name: string;
|
||||
};
|
||||
@@ -14,7 +16,7 @@ type MoveEvent = {
|
||||
};
|
||||
|
||||
type OpArgsMapping = {
|
||||
[OpCode.PING]: {};
|
||||
[OpCode.PING]: PingEvent;
|
||||
[OpCode.HELLO]: HelloEvent;
|
||||
[OpCode.MOVE]: MoveEvent;
|
||||
};
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
type ParseUrlParams<Url> = Url extends `${infer Start}/${infer Rest}`
|
||||
? ParseUrlParams<Start> & ParseUrlParams<Rest>
|
||||
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("/foo/bar", { foo: "asd" });
|
||||
navigate("/hello", {});
|
||||
navigate("/hello/{name}", { name: "foo" });
|
||||
}
|
||||
Reference in new issue
Block a user