Skip to content
Cloudflare Docs

TypeScript example

TypeScript examples

The TypeScriptExample component uses ts-blank-space ↗ to remove TypeScript-specific syntax from your example and provide a JavaScript tab. This reduces maintenance burden by only having a single example to maintain.

This component is automatically used in the GitHubCode component when the lang is set to ts.

Component

2 collapsed lines
// comment to demonstrate
// collapsible sections
export default {
async fetch(req, env, ctx) {
if (req !== "POST") {
return new Response("Method Not Allowed", {
status: 405,
headers: {
Allow: "POST",
},
});
}
await env.KV.put("foo", "bar");
return new Response();
},
};
import { TypeScriptExample } from "~/components";
<TypeScriptExample code={{
collapse: "1-2"
}}>
```ts
// comment to demonstrate
// collapsible sections
interface Environment {
KV: KVNamespace;
}
export default {
async fetch(req, env, ctx): Promise<Response> {
if (req !== "POST") {
return new Response("Method Not Allowed", {
status: 405,
headers: {
"Allow": "POST"
}
});
}
await env.KV.put("foo", "bar");
return new Response();
}
} satisfies ExportedHandler<Environment>
```
</TypeScriptExample>

<TypeScriptExample> Props

filename

type: string

An optional filename, ending in .ts.

.ts will be replaced by .js for the JavaScript tab.

playground

type: boolean

If set to true, a Run Worker in Playground button will appear on the JavaScript tab.

code

type: object

Props to pass to the Expressive Code component ↗.

These props will apply to both code blocks and so options like collapse may not work as expected, as lines may be removed from the TypeScript code.