|
8 | 8 | content: Workers RPC — TypeScript |
9 | 9 | description: How TypeScript types for your Worker or Durable Object's RPC |
10 | 10 | methods are generated and exposed to clients |
11 | | - |
12 | 11 | --- |
13 | 12 |
|
14 | 13 | The types generated by running [`wrangler types`](/workers/languages/typescript/#generate-types) provide the `Service` and `DurableObjectNamespace` types, each of which accepts a single type parameter for the server-side [`WorkerEntrypoint`](/workers/runtime-apis/bindings/service-bindings/rpc) or [`DurableObject`](/durable-objects/best-practices/create-durable-object-stubs-and-send-requests/#call-rpc-methods) types. |
| 14 | +We recommend extending the `Env` type generated in a separate file and providing the type parameter there, so that these are not overwritten when you run `wrangler types` again. |
| 15 | + |
| 16 | +For example, if you had a Worker with bindings to a WorkerEntrypoint called `SumService` and a Durable Object called `Counter`, your `wrangler types` output would look like this: |
15 | 17 |
|
16 | | -Using higher-order types, we automatically generate client-side stub types (e.g., forcing all methods to be async). |
| 18 | +```ts title="worker-configuration.d.ts" |
| 19 | +// Generated by Wrangler by running `wrangler types --env-interface BaseEnv` |
| 20 | +declare namespace Cloudflare { |
| 21 | + interface Env { |
| 22 | + SUM_SERVICE: Fetcher; |
| 23 | + COUNTER_OBJECT: DurableObjectNamespace; |
| 24 | + } |
| 25 | +} |
| 26 | +interface BaseEnv extends Cloudflare.Env {} |
| 27 | +``` |
17 | 28 |
|
18 | | -For example: |
| 29 | +Then extend `Env` type in a separate file: |
19 | 30 |
|
20 | | -```ts |
21 | | -interface Env { |
22 | | - SUM_SERVICE: Service<SumService>; |
23 | | - COUNTER_OBJECT: DurableObjectNamespace<Counter> |
| 31 | +```ts title="env.d.ts" |
| 32 | +interface Env extends BaseEnv { |
| 33 | + SUM_SERVICE: Service<import("../path/to/your/bound/worker").SumService>; |
| 34 | + COUNTER_OBJECT: DurableObjectNamespace<import("../path/to/your/do").Counter>; |
24 | 35 | } |
| 36 | +``` |
| 37 | + |
| 38 | +Using higher-order types, we automatically generate client-side stub types (e.g., forcing all methods to be async). In the following example, `env.SUM_SERVICE.sum` will be typed as defined in the `SumService` WorkerEntrypoint. |
25 | 39 |
|
| 40 | +```ts title="src/index.ts" |
26 | 41 | export default { |
27 | | - async fetch(req, env, ctx): Promise<Response> { |
28 | | - const result = await env.SUM_SERVICE.sum(1, 2); |
29 | | - return new Response(result.toString()); |
30 | | - } |
| 42 | + async fetch(req, env, ctx): Promise<Response> { |
| 43 | + const result = await env.SUM_SERVICE.sum(1, 2); |
| 44 | + return new Response(result.toString()); |
| 45 | + }, |
31 | 46 | } satisfies ExportedHandler<Env>; |
32 | 47 | ``` |
0 commit comments