Skip to content

Commit

Permalink
refactor: update makeURLSearchParams to accept readonly non-`Record…
Browse files Browse the repository at this point in the history
…`s (#8868)
  • Loading branch information
kyranet committed Nov 28, 2022
1 parent ed68a1a commit 8376e2d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
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

0 comments on commit 8376e2d

Please sign in to comment.