Josh CartmellFront-End Engineer Posts

WebC Example

Cloudflare Email Worker TypeScript

I'm working on a project using a Cloudflare Email worker. I wanted to use typescript but as I created the worker it initially seemed like I was forced into using the web editor.

This is my first time using a Cloudflare Worker so I had no idea what was normal or how things worked

Eventually I discovered I could clone the worker code it had generated locally with:

npx create-cloudflare@latest dir-to-clone-into --existing-script name of worker

That gave me with a javascript src/worker.js. So I:

  • changed the extension to .ts
  • copied a tsconfig.json from https://github.com/cloudflare/templates/blob/v4.0.0/d1-template/tsconfig.json
  • updated my wrangler.toml to have compatibility date that matched the wrangler config in the above template
  • ran yarn wrangler types to generate cloudflare worker types

In worker.ts I had code that looks like:

export default {
	async email(message, env, ctx) {
		// implementation
	},
};

All three of the arguments had type errors like:

Parameter 'message' implicitly has an 'any' type.ts(7006)

I noodled on this for some time and discovered ExportedHandler in the generated worker-configuration.d.ts types. I went back to the template and realized I could do what was done there. So now I have:

export default {
	async email(message, env, ctx) {
        // implementation
	},
} satisfies ExportedHandler<Env>;

And the typechecker is happy!