# Type Tables

Generate tables from TypeScript types.

`@vuesho/typescript` generates a table from a type's properties or a Vue component's props, when the site builds. Doc comments become the descriptions:

```md tab="content/button.md"
<auto-type-table path="../src/button.ts" name="ButtonProps" />
```

```ts tab="src/button.ts"
export interface ButtonProps {
  /** The text of the button. */
  label: string;
  /**
   * The size of the button.
   *
   * @defaultValue "md"
   */
  size?: "sm" | "md" | "lg";
  /** Disables the button, so a click does nothing. */
  disabled?: boolean;
}
```

### ButtonProps

| Prop        | Type                                | Description                                |
| ----------- | ----------------------------------- | ------------------------------------------ |
| `label`     | `string`                            | The button's text.                         |
| `size?`     | `"sm" \| "md" \| "lg" \| undefined` | The button's size. Default: `"md"`         |
| `disabled?` | `boolean \| undefined`              | Disables the button, so clicks do nothing. |

A row opens on click to show its full type and description.

## Setup [#setup]

### Install the Packages [#install-the-packages-step]

The package needs TypeScript 6's JavaScript API, which TypeScript 7 doesn't have:

```npm
npm i -D @vuesho/typescript typescript@6
```

### Add the Plugin [#add-the-plugin-step]

```ts title="vuesho.config.ts"
import { autoTypeTablePlugin } from "@vuesho/typescript"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  autoTypeTablePlugin(), // [!code ++]
);
```

## Attributes [#attributes]

`<auto-type-table>` renders the type `name` exported from the file at `path`, as a [`TypeTable`](/markdown/components#type-table). Other attributes, like `class` and `id`, go on the table:

### AutoTypeTableProps

Attributes of `<auto-type-table>` in Markdown.

| Prop    | Type                   | Description                                                                                  |
| ------- | ---------------------- | -------------------------------------------------------------------------------------------- |
| `path?` | `string \| undefined`  | The TypeScript or `.vue` file, relative to the page, or to the working directory with `cwd`. |
| `name?` | `string \| undefined`  | The exported type or component to document.                                                  |
| `type?` | `string \| undefined`  | A TypeScript type, or declarations on several lines that follow the file at `path`.          |
| `cwd?`  | `boolean \| undefined` | Resolves `path` from the working directory instead of the page. Default: `false`             |

Write `path`, `name`, `type` and `id` as plain attributes, since a bound one, like `:path`, makes the page fail to compile. A type error fails the build at the tag's line, with TypeScript's message.

In the page's [Markdown version](/ai), each type table is a Markdown table with the full types. Search indexes each row.

## Inline Types [#inline-types]

`type` takes a type instead of a file. With `path`, the code in `type` is added to the end of the file, and `name` names a type in it:

```md
<auto-type-table type="{ size: number; label?: string }" />

<auto-type-table
  path="../src/button.ts"
  type="import type { Icon } from './icon';
export type IconButtonProps = ButtonProps & { icon: Icon };"
  name="IconButtonProps"
/>
```

## Vue Components [#vue-components]

When `path` points to a `.vue` file, the table lists the component's props, without the attributes every element takes, like `class`. `name` names an export, and defaults to the default export.

```md
<auto-type-table path="../src/components/Button.vue" />
```

## Doc Comments [#doc-comments]

A description is Markdown. `{@link}` and `{@linkplain}` render as their text, or the name they link. `{@linkcode}` renders as code. A link to a URL renders as a link. These tags change a row:

| Tag                         | Effect                                                                   |
| --------------------------- | ------------------------------------------------------------------------ |
| `@defaultValue`, `@default` | Sets the default value                                                   |
| `@deprecated`               | Strikes through the property's name                                      |
| `@param`, `@returns`        | Describes a function's parameters and result                             |
| `@internal`                 | Leaves the property out of the table                                     |
| `@remarks`                  | Inline code at its start, like ``@remarks `Size` ``, sets the short type |
| `@fumadocsType`             | Inline code sets the full type                                           |
| `@fumadocsHref`             | Links the type to a URL                                                  |

`@example` and `@see` aren't shown in the description. `transform` can read them from an entry's tags and append them to it.

## Custom Pages [#custom-pages]

In a [custom page](/custom-pages), read the properties with `generateTypeTable()` on a generator from `createGenerator()`, and display them with `TypeTable`. The `path` that `generateTypeTable()` takes is relative to the working directory:

```ts title="src/server/types.ts"
import { createGenerator } from "@vuesho/typescript";
import type { TypeNode } from "vuesho/ui/components/type-table";

const generator = createGenerator();

export function buttonProps(): Record<string, TypeNode> {
  const [doc] = generator.generateTypeTable({ path: "src/button.ts", name: "ButtonProps" });
  const type: Record<string, TypeNode> = {};
  for (const entry of doc!.entries) {
    type[entry.name] = {
      type: entry.simplifiedType,
      typeDescription: entry.type,
      // The doc comment, as plain text.
      description: entry.description,
      default: entry.tags.find((tag) => tag.name === "defaultValue")?.text,
      required: entry.required,
      deprecated: entry.deprecated,
    };
  }
  return type;
}
```

```vue title="src/pages/button.vue"
<script setup lang="ts">
import { definePage } from "vuesho/client";
import { TypeTable } from "vuesho/components";
import type { TypeNode } from "vuesho/ui/components/type-table";
import { buttonProps } from "../server/types";

definePage({
  data: { title: "Button" },
  // Runs when the site builds.
  props: () => ({ type: buttonProps() }),
});
defineProps<{ type: Record<string, TypeNode> }>();
</script>

<template>
  <TypeTable :type="type" />
</template>
```

## Options [#options]

### AutoTypeTablePluginOptions

| Prop              | Type                                 | Description                                                                         |
| ----------------- | ------------------------------------ | ----------------------------------------------------------------------------------- |
| `generator?`      | `Generator \| undefined`             | The table generator, which your server code can share. Default: `createGenerator()` |
| `allowInternal?`  | `boolean \| undefined`               | Keeps properties marked `@internal`. Default: `false`                               |
| `transform?`      | `Transformer \| undefined`           | Changes each entry.                                                                 |
| `typeSimplifier?` | `TypeSimplifierOptions \| undefined` | How an entry's short type is written.                                               |

The generator reads the `tsconfig.json` in the working directory, unless `tsconfigPath` points to another.

### Short Types [#short-types]

A closed row shows a short type, like `union`, and opens to show the full type. `typeSimplifier` writes the short types. This one keeps the full type when it's short:

```ts title="vuesho.config.ts"
import { autoTypeTablePlugin } from "@vuesho/typescript";

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  autoTypeTablePlugin({
    typeSimplifier: {
      override({ type, checker, location }) {
        const text = checker.typeToString(type, location).replace(/ \| undefined$/, "");
        if (text.length <= 32 && !text.includes("=>")) return text;
      },
    },
  }),
);
```

### Caching [#caching]

`generatorFileCache()` saves the tables in `node_modules/.vuesho/typescript`, or in the folder of `dir`, so the next build and `vuesho dev` read them instead of running TypeScript. A cached table is generated again when its file, a file it imports, or an option other than a function changes:

```ts title="vuesho.config.ts"
import { autoTypeTablePlugin, createGenerator, generatorFileCache } from "@vuesho/typescript";

const generator = createGenerator({ cache: generatorFileCache() });

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  autoTypeTablePlugin({ generator }), // [!code highlight]
);
```
