Skip to content

fix type checking when strictNullChecks is disabled #1833

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 12, 2024
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
7 changes: 7 additions & 0 deletions .changeset/lazy-dancers-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"openapi-typescript-helpers": patch
"openapi-react-query": patch
"openapi-fetch": patch
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I view this as a bug fix that implements the expected behavior. However, it does have the potential to break type checking in projects with incorrect code, so I can change this to minor if we want to be safe.

---

Fix identification of required properties when `strictNullChecks` is disabled
1 change: 1 addition & 0 deletions packages/openapi-fetch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
"test": "pnpm run \"/^test:/\"",
"test:js": "vitest run",
"test:ts": "tsc --noEmit",
"test:ts-no-strict": "tsc --noEmit -p test/no-strict-null-checks/tsconfig.json",
"test-e2e": "playwright test",
"e2e-vite-build": "vite build test/fixtures/e2e",
"e2e-vite-start": "vite preview test/fixtures/e2e",
Expand Down
11 changes: 6 additions & 5 deletions packages/openapi-fetch/src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type {
ErrorResponse,
FilterKeys,
HasRequiredKeys,
HttpMethod,
IsOperationRequestBodyOptional,
MediaType,
OperationRequestBodyContent,
PathsWithMethod,
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,
} from "openapi-typescript-helpers";

Expand Down Expand Up @@ -82,14 +83,14 @@ export interface DefaultParamsOption {
export type ParamsOption<T> = T extends {
parameters: any;
}
? HasRequiredKeys<T["parameters"]> extends never
? RequiredKeysOf<T["parameters"]> extends never
? { params?: T["parameters"] }
: { params: T["parameters"] }
: DefaultParamsOption;

export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never
? { body?: never }
: undefined extends OperationRequestBodyContent<T>
: IsOperationRequestBodyOptional<T> extends true
? { body?: OperationRequestBodyContent<T> }
: { body: OperationRequestBodyContent<T> };

Expand Down Expand Up @@ -150,7 +151,7 @@ export interface Middleware {
}

/** This type helper makes the 2nd function param required if params/requestBody are required; otherwise, optional */
export type MaybeOptionalInit<Params extends Record<HttpMethod, {}>, Location extends keyof Params> = HasRequiredKeys<
export type MaybeOptionalInit<Params extends Record<HttpMethod, {}>, Location extends keyof Params> = RequiredKeysOf<
FetchOptions<FilterKeys<Params, Location>>
> extends never
? FetchOptions<FilterKeys<Params, Location>> | undefined
Expand All @@ -160,7 +161,7 @@ export type MaybeOptionalInit<Params extends Record<HttpMethod, {}>, Location ex
// - Determines if the param is optional or not.
// - Performs arbitrary [key: string] addition.
// Note: the addition It MUST happen after all the inference happens (otherwise TS can’t infer if init is required or not).
type InitParam<Init> = HasRequiredKeys<Init> extends never
type InitParam<Init> = RequiredKeysOf<Init> extends never
? [(Init & { [key: string]: unknown })?]
: [Init & { [key: string]: unknown }];

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { afterAll, beforeAll, describe, it } from "vitest";
import createClient from "../../src/index.js";
import { server, baseUrl, useMockRequestHandler } from "../fixtures/mock-server.js";
import type { paths } from "../fixtures/api.js";

beforeAll(() => {
server.listen({
onUnhandledRequest: (request) => {
throw new Error(`No request handler found for ${request.method} ${request.url}`);
},
});
});

afterEach(() => server.resetHandlers());

afterAll(() => server.close());

describe("client", () => {
describe("TypeScript checks", () => {
describe("params", () => {
it("is optional if no parameters are defined", async () => {
const client = createClient<paths>({
baseUrl,
});

useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { message: "OK" },
});

// assert no type error
await client.GET("/self");

// assert no type error with empty params
await client.GET("/self", { params: {} });
});

it("checks types of optional params", async () => {
const client = createClient<paths>({
baseUrl,
});

useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { message: "OK" },
});

// assert no type error with no params
await client.GET("/blogposts");

// assert no type error with empty params
await client.GET("/blogposts", { params: {} });

// expect error on incorrect param type
// @ts-expect-error
await client.GET("/blogposts", { params: { query: { published: "yes" } } });

// expect error on extra params
// @ts-expect-error
await client.GET("/blogposts", { params: { query: { fake: true } } });
});
});

describe("body", () => {
it("requires necessary requestBodies", async () => {
const client = createClient<paths>({ baseUrl });

useMockRequestHandler({
baseUrl,
method: "put",
path: "/blogposts",
});

// expect error on missing `body`
// @ts-expect-error
await client.PUT("/blogposts");

// expect error on missing fields
// @ts-expect-error
await client.PUT("/blogposts", { body: { title: "Foo" } });

// (no error)
await client.PUT("/blogposts", {
body: {
title: "Foo",
body: "Bar",
publish_date: new Date("2023-04-01T12:00:00Z").getTime(),
},
});
});

it("requestBody with required: false", async () => {
const client = createClient<paths>({ baseUrl });

useMockRequestHandler({
baseUrl,
method: "put",
path: "/blogposts-optional",
status: 201,
});

// assert missing `body` doesn’t raise a TS error
await client.PUT("/blogposts-optional");

// assert error on type mismatch
// @ts-expect-error
await client.PUT("/blogposts-optional", { body: { error: true } });

// (no error)
await client.PUT("/blogposts-optional", {
body: {
title: "",
publish_date: 3,
body: "",
},
});
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"strictNullChecks": false
},
"include": ["."],
"exclude": []
}
2 changes: 1 addition & 1 deletion packages/openapi-fetch/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
"types": ["vitest/globals"]
},
"include": ["src", "test"],
"exclude": ["examples", "node_modules"]
"exclude": ["examples", "node_modules", "test/no-strict-null-checks"]
}
6 changes: 3 additions & 3 deletions packages/openapi-react-query/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
useSuspenseQuery,
} from "@tanstack/react-query";
import type { ClientMethod, FetchResponse, MaybeOptionalInit, Client as FetchClient } from "openapi-fetch";
import type { HasRequiredKeys, HttpMethod, MediaType, PathsWithMethod } from "openapi-typescript-helpers";
import type { HttpMethod, MediaType, PathsWithMethod, RequiredKeysOf } from "openapi-typescript-helpers";

export type UseQueryMethod<Paths extends Record<string, Record<HttpMethod, {}>>, Media extends MediaType> = <
Method extends HttpMethod,
Expand All @@ -22,7 +22,7 @@ export type UseQueryMethod<Paths extends Record<string, Record<HttpMethod, {}>>,
>(
method: Method,
url: Path,
...[init, options, queryClient]: HasRequiredKeys<Init> extends never
...[init, options, queryClient]: RequiredKeysOf<Init> extends never
? [(Init & { [key: string]: unknown })?, Options?, QueryClient?]
: [Init & { [key: string]: unknown }, Options?, QueryClient?]
) => UseQueryResult<Response["data"], Response["error"]>;
Expand All @@ -36,7 +36,7 @@ export type UseSuspenseQueryMethod<Paths extends Record<string, Record<HttpMetho
>(
method: Method,
url: Path,
...[init, options, queryClient]: HasRequiredKeys<Init> extends never
...[init, options, queryClient]: RequiredKeysOf<Init> extends never
? [(Init & { [key: string]: unknown })?, Options?, QueryClient?]
: [Init & { [key: string]: unknown }, Options?, QueryClient?]
) => UseSuspenseQueryResult<Response["data"], Response["error"]>;
Expand Down
31 changes: 26 additions & 5 deletions packages/openapi-typescript-helpers/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,17 @@ export type ResponseObjectMap<T> = T extends { responses: any } ? T["responses"]
/** Return `content` for a Response Object */
export type ResponseContent<T> = T extends { content: any } ? T["content"] : unknown;

/** Return `requestBody` for an Operation Object */
export type OperationRequestBody<T> = T extends { requestBody?: any } ? T["requestBody"] : never;
/** Return type of `requestBody` for an Operation Object */
export type OperationRequestBody<T> = "requestBody" extends keyof T ? T["requestBody"] : never;

/** Internal helper to get object type with only the `requestBody` property */
type PickRequestBody<T> = "requestBody" extends keyof T ? Pick<T, "requestBody"> : never;

/** Resolve to `true` if request body is optional, else `false` */
export type IsOperationRequestBodyOptional<T> = RequiredKeysOf<PickRequestBody<T>> extends never ? true : false;

/** Internal helper used in OperationRequestBodyContent */
export type OperationRequestBodyMediaContent<T> = undefined extends OperationRequestBody<T>
export type OperationRequestBodyMediaContent<T> = IsOperationRequestBodyOptional<T> extends true
? ResponseContent<NonNullable<OperationRequestBody<T>>> | undefined
: ResponseContent<OperationRequestBody<T>>;

Expand Down Expand Up @@ -152,7 +158,22 @@ export type GetValueWithDefault<Obj, KeyPattern, Default> = Obj extends any
export type MediaType = `${string}/${string}`;
/** Return any media type containing "json" (works for "application/json", "application/vnd.api+json", "application/vnd.oai.openapi+json") */
export type JSONLike<T> = FilterKeys<T, `${string}/json`>;
/** Filter objects that have required keys */

/**
* Filter objects that have required keys
* @deprecated Use `RequiredKeysOf` instead
*/
export type FindRequiredKeys<T, K extends keyof T> = K extends unknown ? (undefined extends T[K] ? never : K) : K;
/** Does this object contain required keys? */
/**
* Does this object contain required keys?
* @deprecated Use `RequiredKeysOf` instead
*/
export type HasRequiredKeys<T> = FindRequiredKeys<T, keyof T>;

/** Helper to get the required keys of an object. If no keys are required, will be `undefined` with strictNullChecks enabled, else `never` */
type RequiredKeysOfHelper<T> = {
// biome-ignore lint/complexity/noBannedTypes: `{}` is necessary here
[K in keyof T]: {} extends Pick<T, K> ? never : K;
}[keyof T];
/** Get the required keys of an object, or `never` if no keys are required */
export type RequiredKeysOf<T> = RequiredKeysOfHelper<T> extends undefined ? never : RequiredKeysOfHelper<T>;