#Proper typing for global Cloudflare KV variables

1 messages · Page 1 of 1 (latest)

small talon
#

The Cloudflare runtime exposes KV namespaces as global variables, so you can have loader functions like so:

export const loader: LoaderFunction = async ({ params }: LoaderArgs) => {
    let initialData = await MY_KV_NAMESPACE.get(params.slug, { type: 'json' })
}```
Typescript, of course, doesn't know about these global variables, so `MY_KV_NAMESPACE` above is undefined and untyped. What is the correct way to type these? Currently, I have a `globals.d.ts` file with the following:

```js
declare const MY_KV_NAMESPACE: any```
Then, in routes where I'm using `MY_KV_NAMESPACE` in my loader, I have 

```js
import { MY_KV_NAMESPACE } from '~/types/globals'```
Is there a more correct way to handle this? (I've searched the discord, haven't found anything.)
small talon
#

Just realized that declare const MY_KV_NAMESPACE: any actually results in a build error, because I'm not importing as a type. So my solution above is a no-go.

#

Looks like @cloudflare/workers-types provides a KVNamespace type, which is great. So I guess my question now is, how do I use it? The global MY_KV_NAMESPACE variable is never defined in my code, so I'm not sure how to resolve the issue and assign it the type KVNamespace