Skip to content
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

refactor: update makeURLSearchParams to accept readonly non-Records #8868

Merged
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
27 changes: 27 additions & 0 deletions packages/rest/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,31 @@ describe('makeURLSearchParams', () => {
expect([...params.entries()]).toEqual([['foo', 'bar']]);
});
});

describe('types', () => {
interface TestInput {
foo: string;
}

test("GIVEN object without index signature THEN TypeScript doesn't raise a type error", () => {
// Previously, `makeURLSearchParams` used `Record<string, unknown>` as an input, but that meant that it
// couldn't accept most interfaces, since they don't have an index signature. This test is to make sure
// non-Records can be used without casting.

const input = { foo: 'bar' } as TestInput;
const params = makeURLSearchParams(input);

expect([...params.entries()]).toEqual([['foo', 'bar']]);
});

test("GIVEN readonly object on a non-readonly generic type THEN TypeScript doesn't raise a type error", () => {
// While `Readonly<T>` type was always accepted in `makeURLSearchParams`, this test is to ensure that we can
// use the generic type and accept `Readonly<T>` rather than only [possibly] mutable `T`.

const input = Object.freeze({ foo: 'bar' } as TestInput);
const params = makeURLSearchParams<TestInput>(input);

expect([...params.entries()]).toEqual([['foo', 'bar']]);
});
});
});
2 changes: 1 addition & 1 deletion packages/rest/src/lib/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function serializeSearchParam(value: unknown): string | null {
* @param options - The options to use
* @returns A populated URLSearchParams instance
*/
export function makeURLSearchParams(options?: Record<string, unknown>) {
export function makeURLSearchParams<T extends object>(options?: Readonly<T>) {
const params = new URLSearchParams();
if (!options) return params;

Expand Down