cloudflare / workers-types

TypeScript type definitions for authoring Cloudflare Workers.
BSD 3-Clause "New" or "Revised" License
359 stars 89 forks source link

Get type hints on incoming Request object #309

Closed thexeos closed 1 year ago

thexeos commented 1 year ago

I tried the suggestion from #85, which made IncomingRequestCfProperties available globally, but if I try to read event.request.cf, I get:

Property 'cf' does not exist on type 'Request'.

I also tried const request = event.request as Request, but this Request is not the class from this package.

How can I get type hints to work?

thexeos commented 1 year ago

Also, not sure if related, but after forcing the type with const cf = (event.request as any).cf as IncomingRequestCfProperties, trying to access cf.country leads to

Property 'country' does not exist on type 'IncomingRequestCfProperties<unknown>'.
  Property 'country' does not exist on type 'IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<...> & IncomingRequestCfPropertiesCloudflareAccessOrApiShield'.

Note how IncomingRequestCfPropertiesGeographicInformation is not included in the derived type definition, yet I see it included in this repo.

Is this something that you can reproduce?

thexeos commented 1 year ago

Upon some further investigation, it seems like Request from lib.dom.d.ts always takes precedence.

image

Even though the custom Request is defined in the same file, as it is not namespaced in any way, the custom definition is not used.

philipatkinson commented 1 year ago

I have a feeling that this is the same issue as #311 (certainly the 'country does not exist' error is the same one you get with the most recent release). #310 (my pull request with the fix) might therefore be the solution.

mrbbot commented 1 year ago

Hey! 👋 @cloudflare/workers-types is not compatible with lib.dom.d.ts. Make sure you're tsconfig.json looks something like:

{
  "compilerOptions": {
    ...
    "lib": ["ES2020"],
    "types": ["@cloudflare/workers-types"]
  }
}