Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
"stub": "unbuild --stub",
"test": "pnpm lint && pnpm vitest run",
"test:fixture:types": "pnpm stub && jiti ./test/scripts/gen-fixture-types.ts && cd test/fixture && tsc --noEmit",
"test:types": "tsc --noEmit && pnpm test:fixture:types"
"test:types": "tsc --noEmit && tsc --noEmit -p test/types-stress && pnpm test:fixture:types"
},
"resolutions": {
"nitropack": "link:."
Expand Down
50 changes: 32 additions & 18 deletions src/types/fetch/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,28 +24,42 @@ export type TypedInternalResponse<
> = Default extends string | boolean | number | null | void | object
? // Allow user overrides
Default
: Route extends string
? MiddlewareOf<Route, Method> extends never
? MiddlewareOf<Route, "default"> extends never
? // Bail if only types are Error or void (for example, from middleware)
Default
: MiddlewareOf<Route, "default">
: MiddlewareOf<Route, Method>
: // Not distributive over `Route`: with a generic `Default` the check above is deferred, and
// TypeScript would compute the constraint of a distributive type over every `InternalApi` key.
[Route] extends [string]
? _TypedInternalResponse<Route, Default, Method>
: Default;

type _TypedInternalResponse<
Route extends string,
Default,
Method extends RouterMethod,
> = Route extends string
? MiddlewareOf<Route, Method> extends never
? MiddlewareOf<Route, "default"> extends never
? // Bail if only types are Error or void (for example, from middleware)
Default
: MiddlewareOf<Route, "default">
: MiddlewareOf<Route, Method>
: Default;

// Extracts the available http methods based on the route.
// Defaults to all methods if there aren't any methods available or if there is a catch-all route.
export type AvailableRouterMethod<R extends NitroFetchRequest> =
R extends string
? keyof InternalApi[MatchedRoutes<R>] extends undefined
? RouterMethod
: Extract<
keyof InternalApi[MatchedRoutes<R>],
"default"
> extends undefined
? Extract<RouterMethod, keyof InternalApi[MatchedRoutes<R>]>
: RouterMethod
: RouterMethod;
// Not distributive itself, so TypeScript never computes its constraint over every `InternalApi` key,
// while `_AvailableRouterMethod` still distributes over each member of a union of routes.
export type AvailableRouterMethod<R extends NitroFetchRequest> = [R] extends [
string,
]
? _AvailableRouterMethod<R>
: RouterMethod;

type _AvailableRouterMethod<R extends string> = R extends string
? keyof InternalApi[MatchedRoutes<R>] extends undefined
? RouterMethod
: Extract<keyof InternalApi[MatchedRoutes<R>], "default"> extends undefined
? Extract<RouterMethod, keyof InternalApi[MatchedRoutes<R>]>
: RouterMethod
: RouterMethod;

// Argumented fetch options to include the correct request methods.
// This overrides the default, which is only narrowed to a string.
Expand Down
15 changes: 15 additions & 0 deletions test/fixture/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ const $fetch = {} as $Fetch;
describe("API routes", () => {
const dynamicString: string = "";

it("keeps a generic response type in generic functions", () => {
async function getGeneric<T>(url: string) {
return await $fetch<T>(url);
}
async function getCast<T>(url: string): Promise<T> {
return (await $fetch(url)) as T;
}
expectTypeOf(getGeneric<TestResponse>("/test")).toEqualTypeOf<
Promise<TestResponse>
>();
expectTypeOf(getCast<TestResponse>("/test")).toEqualTypeOf<
Promise<TestResponse>
>();
});

it("generates types for middleware, unknown and manual typed routes", () => {
expectTypeOf($fetch("/")).toEqualTypeOf<Promise<unknown>>(); // middleware
expectTypeOf($fetch("/api/unknown")).toEqualTypeOf<Promise<unknown>>();
Expand Down
55 changes: 55 additions & 0 deletions test/types-stress/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { expectTypeOf } from "expect-type";
import type { $Fetch } from "nitropack/types";

// 400 typed routes: enough for generic `$fetch` calls to fail with
// `TS2589: Type instantiation is excessively deep and possibly infinite` when
// `TypedInternalResponse` / `AvailableRouterMethod` distribute over every route.
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
type N = `${Digit}${Digit}`;
type StressRoutes = {
[K in `/api/param/${N}/:id`]: { get: { route: K } };
} & {
[K in `/api/methods/${N}`]: { default: { route: K }; post: { posted: K } };
} & {
[K in `/api/glob/${N}/**`]: { default: { route: K } };
} & {
[K in `/api/get/${N}`]: { get: { route: K } };
};

declare module "nitropack/types" {
interface InternalApi extends StressRoutes {}
}

declare const $fetch: $Fetch;

interface TestResponse {
message: string;
}

async function getGeneric<T>(url: string) {
return await $fetch<T>(url);
}
async function getCast<T>(url: string): Promise<T> {
return (await $fetch(url)) as T;
}

// Only type-checked, never run
export function typeTests() {
expectTypeOf(getGeneric<TestResponse>("/test")).toEqualTypeOf<
Promise<TestResponse>
>();
expectTypeOf(getCast<TestResponse>("/test")).toEqualTypeOf<
Promise<TestResponse>
>();

// The routes above are registered and still resolve
expectTypeOf($fetch("/api/methods/42")).toEqualTypeOf<
Promise<{ route: "/api/methods/42" }>
>();
expectTypeOf($fetch("/api/methods/42", { method: "POST" })).toEqualTypeOf<
Promise<{ posted: "/api/methods/42" }>
>();
expectTypeOf($fetch("/api/param/42/abc")).toEqualTypeOf<
Promise<{ route: "/api/param/42/:id" }>
>();
}
7 changes: 7 additions & 0 deletions test/types-stress/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
// Type checks with many typed routes, isolated from the fixture so the extra
// `InternalApi` routes don't change what the fixture's route types resolve to.
"extends": "../../tsconfig.json",
"include": ["."],
"exclude": []
}
8 changes: 7 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,11 @@
}
},
"include": ["src", "test", "scripts/gen-mirror.ts"],
"exclude": ["dist", "examples", "playground", "test/fixture"]
"exclude": [
"dist",
"examples",
"playground",
"test/fixture",
"test/types-stress"
]
}
Loading