Skip to content

fix(RequestInit): restrict body type based on method to improve type safety #1953

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

Closed
wants to merge 2 commits into from

Conversation

Bashamega
Copy link
Contributor

fixes #1678

Copy link
Contributor

Thanks for the PR!

This section of the codebase is owned by @saschanaz - if they write a comment saying "LGTM" then it will be merged.

@Bashamega Bashamega marked this pull request as ready for review March 30, 2025 14:35
@@ -1953,7 +1953,7 @@ interface ReportingObserverOptions {

interface RequestInit {
/** A BodyInit object or null to set request's body. */
body?: BodyInit | null;
body?: 'GET' | 'HEAD' extends this['method'] ? never : BodyInit | null | null;
Copy link
Contributor

Choose a reason for hiding this comment

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

This won't work if method is a general string, e.g.:

function download(url: URL, method: string, body: any) {
  return fetch(url, { method, body });
}

Or method is lowercased or something weird like "gET" (this still works in browsers as the browser internally makes it uppercase). Actually not sure this would work even if method is GET/HEAD, can you add a unit test?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Actually, when I think about it more, it seems that this is a missing feature in TypeScript. TS needs to have a Template Literal Type for case-insensitive matching.

@Bashamega Bashamega closed this Apr 3, 2025
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.

fetch type "GET" or "HEAD" with a body should be a type error
2 participants