跳转到主要内容

TypeScript example

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.

:::note Some TypeScript syntax influences runtime behaviour, and cannot be stripped.

Please refer to the Unsupported Syntax section of the project's README. :::

:::caution Code blocks are typically configured with options on the opening fence, like so:

```ts collapse={1-2}
// ...
```

These cannot be extracted by TypeScriptExample so they must be moved to the code prop.

<TypeScriptExample code={{
  collapse: "1-2"
}}>
```ts
// ...
```
</TypeScriptExample>

:::

Component

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 Astro 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.