Skip to content

Commit

Permalink
fix(ts): make ReadonlyHeaders more compatible with Headers (#49075)
Browse files Browse the repository at this point in the history
### What?

Make it possible to pass `headers()` where the `Headers` type is
expected. An example would be `fetch`:

```ts
import { headers } from "next/headers"
// ...
fetch("https://example.com", {
  headers: headers()
})
```

### Why?

`ReadonlyHeaders` _currently omits_ some mutating methods which make
sense since they don't make sense. 🙃. However, it makes
it necessary to pass the result anywhere where `Headers` is expected.
Since we already throw errors when these methods are called illegally,
we can make the type constraint a bit looser to avoid `as any` or
`Object.fromEntries(headers())` or similar.

### How?

Mark the unavailable methods as `@deprecated` which will visually mark
them in IDEs:


![image](https://user-images.githubusercontent.com/18369201/235621140-3df8b10a-b90f-4ec3-b218-066303bfbc73.png)


Closes NEXT-1075
  • Loading branch information
balazsorban44 committed May 3, 2023
1 parent 70c6f94 commit 79ef1d6
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions packages/next/src/server/web/spec-extension/adapters/headers.ts
Expand Up @@ -17,8 +17,14 @@ export class ReadonlyHeadersError extends Error {
}
}

export type ReadonlyHeaders = Omit<Headers, 'append' | 'delete' | 'set'>

export type ReadonlyHeaders = Headers & {
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/api-reference/headers */
append(...args: any[]): void
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/api-reference/headers */
set(...args: any[]): void
/** @deprecated Method unavailable on `ReadonlyHeaders`. Read more: https://nextjs.org/docs/api-reference/headers */
delete(...args: any[]): void
}
export class HeadersAdapter extends Headers {
private readonly headers: IncomingHttpHeaders

Expand Down

0 comments on commit 79ef1d6

Please sign in to comment.