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

This commit is contained in:
Aura Román
2022-11-28 09:20:27 +01:00
committed by GitHub
parent ed68a1af5b
commit 8376e2dbcd
2 changed files with 28 additions and 1 deletions

View File

@@ -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']]);
});
});
});

View File

@@ -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;