Skip to content

Type getJson() for every JSON value, with an optional type argument - #216

Open
theluckystrike wants to merge 1 commit into
httptoolkit:mainfrom
theluckystrike:fix/mockttp-getjson-type
Open

theluckystrike wants to merge 1 commit into
httptoolkit:mainfrom
theluckystrike:fix/mockttp-getjson-type

Conversation

@theluckystrike

Copy link
Copy Markdown
Contributor

This follows the shape you suggested in #155. getJson() on CompletedBody was typed as Promise<object | undefined>, so a JSON array was fine but a body of 42, "text", true or null was typed wrong, and callers had to cast through unknown to name their own type.

It's now getJson<R = object | string | number | boolean | null>(): Promise<R | undefined>. The default covers every value JSON.parse can return, with no any. Callers can pass their own type, like getJson<{ id: number }>(). undefined still means the body couldn't be decoded or parsed, and the doc comment now says so.

I used object rather than {} | [] because of the point leumasme raised: {} also accepts primitives and [] is only the empty tuple. Arrays are still covered by object. The one break is code like if (json && 'x' in json), since the type now includes primitives.

Added .json tests to request-utils.spec.ts for an object, an array, a number, null, invalid JSON and an unknown encoding, plus one call with an explicit type argument. On main that spec fails to compile (TS2558, expected 0 type arguments) because getJson takes no type argument there. With this change npm run build:src is clean and npm run test:node gives 842 passing, 0 failing. I didn't run the browser tests.

Closes #155

getJson() was typed as Promise<object | undefined>, so bodies like 42,
"text", true or null got the wrong type, and callers couldn't name the
type they expect without casting through unknown. It's now generic:
getJson<R = object | string | number | boolean | null>(), still
returning undefined when the body can't be decoded or parsed (httptoolkit#155).

New .json tests in request-utils.spec.ts cover an object, an array, a
number, null, invalid JSON, an unknown encoding and an explicit type
argument. On main the spec doesn't compile (TS2558: Expected 0 type
arguments, but got 1). With this change it passes (16 passing), tsc
builds cleanly and the full test:node run gives 842 passing, 0 failing.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect return type for CompletedBody.getJson

1 participant