Skip to content

feat: add generic type to json method#5436

Closed
rtritto wants to merge 2 commits into
nodejs:mainfrom
rtritto:feat-generic-json
Closed

feat: add generic type to json method#5436
rtritto wants to merge 2 commits into
nodejs:mainfrom
rtritto:feat-generic-json

Conversation

@rtritto

@rtritto rtritto commented Jun 17, 2026

Copy link
Copy Markdown

Features

Add support of generic type for json method of fetch and request.

Example

import { request } from 'undici'
const response = await request('URL')
const json = await response.body.json<{ data: 'myDataType' }>()

// ---

import { fetch } from 'undici'
const response = await fetch('URL')
const json = await response.json<{ data: 'myDataType' }>()

Status

Copilot AI review requested due to automatic review settings June 17, 2026 12:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot wasn't able to review any files in this pull request.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@rtritto rtritto changed the title feat: add generic type to json method feat: add generic type to json method Jun 17, 2026
@Zamralik

Zamralik commented Jun 17, 2026

Copy link
Copy Markdown

The json method do not provide a mean to validate the resulting value and it cannot guarantee what the received data are.
It is equivalent to using as, but passing the burden of "lying" about the type to the json method.

const json = await response.body.json() as { data: 'myDataType' };

Worse, it would implicitly cause the type to be erroneously "lied" about when used this way:

const json: { data: 'myDataType' } = await response.body.json();

As typescript implicitly fills the generic to .json<{ data: 'myDataType' }()

It may lead to implicit bugs and vulnerabilities from assuming the incoming data match the expected type.

@KhafraDev

Copy link
Copy Markdown
Member

similar PRs have been rejected, you can find the reason we declined this in those PRs

@KhafraDev KhafraDev closed this Jun 17, 2026
@rtritto rtritto deleted the feat-generic-json branch June 17, 2026 13:51
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.

4 participants