Cloudflare DevelopersCD
Cloudflare Developers7mo ago
1 reply
Exodus

Worker service binding RPC TypeScript types

This question is about how to get TypeScript to recognize an RPC method in a service binding worker. Both workers were created in the last week. E.g.

// worker B, index.tsx
import { WorkerEntrypoint } from 'cloudflare:workers'

export interface EmailSenderMethods {
  sendVerificationCode(params: SendVerificationCode): Promise<void>
}

interface SendVerificationCode {
  code: string
  email: string
  authActionType: 'signup' | 'login'
}

export default class EmailSender
  extends WorkerEntrypoint<Env>
{
  fetch() {
    return new Response('Hello from email worker')
  }

  async sendVerificationCode({
    code,
    email
  }: SendVerificationCode) {}
}

export { EmailSender }


// Worker A, which calls B
// wrangler.jsonc
"services": [
    {
      "binding": "sendEmailWorker",
      "service": "B",
      "entrypoint": "EmailSender"
    }
  ]

// worker-configuration.d.ts after running:
// wrangler types -c wrangler.jsonc -c ../send-email/wrangler.jsonc
declare namespace Cloudflare {
    interface Env {
        sendEmailWorker: Service<import("../send-email/src/index").EmailSender>;
    }
}
interface Env extends Cloudflare.Env {}


Then in Worker A, TypeScript knows that env.sendEmailWorker is valid, but it is of type
any
, and so the sendVerificationCode method is not available.

What's the correct way to type RPC methods in service bindings like these?
Was this page helpful?