fix: allow Data to be inferred from Handler function (#2916)
This PR adds support for single-function GET handler data to be inferred
when using `define.page<typeof handler>()`.
```ts
export const handler = define.handlers((ctx) => {
return page({ foo: "foo" });
});
export default define.page<typeof handler>((ctx) => {
ctx.data; // Correctly resolves as { foo: string }
});
```
This PR also adds a test that checks that the types inferred are correct
by type checking.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { expect } from "@std/expect";
|
||||
import { createDefine } from "./define.ts";
|
||||
import { page } from "./handlers.ts";
|
||||
|
||||
Deno.test.ignore("createDefine", () => {
|
||||
const define = createDefine<{ foo: number }>();
|
||||
|
||||
// Testing the types
|
||||
const handlerFn = define.handlers((ctx) => {
|
||||
ctx.state.foo satisfies number;
|
||||
return page({ bar: true });
|
||||
});
|
||||
const handlerObj = define.handlers({
|
||||
GET(ctx) {
|
||||
ctx.state.foo satisfies number;
|
||||
return page({ bar: [1, 2, 3] });
|
||||
},
|
||||
POST: () => {
|
||||
return page({ baz: "hello" });
|
||||
},
|
||||
});
|
||||
|
||||
define.page<typeof handlerFn>(({ data }) => {
|
||||
data.bar satisfies boolean;
|
||||
return "page";
|
||||
});
|
||||
|
||||
define.page<typeof handlerObj>(({ data }) => {
|
||||
if ("baz" in data) {
|
||||
data.baz satisfies string;
|
||||
} else {
|
||||
data.bar satisfies number[];
|
||||
}
|
||||
return "page";
|
||||
});
|
||||
|
||||
define.middleware((ctx) => {
|
||||
ctx.state.foo satisfies number;
|
||||
return new Response("Hello");
|
||||
});
|
||||
|
||||
expect(typeof define.page).toBe("function");
|
||||
expect(typeof define.handlers).toBe("function");
|
||||
expect(typeof define.middleware).toBe("function");
|
||||
});
|
||||
Reference in New Issue
Block a user