Skip to content

Custom Document Class Configuration

Johannes Loher edited this page Dec 5, 2021 · 1 revision

Configuring Custom Document Class Types

The foundry-vtt-types allow you to configure your own custom document class types to be used throughout most of the type definitions. This means that once you set this up correctly, you should need much fewer type assertions when using parts of the Foundry VTT API that work with instances of these classes because they will already have the correct type automatically.

To achieve this, declaration merging is used to inject your own types into the provided type definitions.

To configure your own document class type to be used, simply follow this structure:

export class <CustomDocumentClass> extends <DocumentClass> { /* ... */ }

declare global {
  interface DocumentClassConfig {
    <DocumentClass>: typeof <CustomDocumentClass>;
  }
}

Be aware that this does not have any runtime effect, you still need to configure your document class to actually be used at runtime in the init hook:

Hooks.once('init', () => {
  CONFIG.<DocumentClass>.documentClass = <CustomDocumentClass>;
});

⚠️ It is of uttermost importance that you always keep the type configuration and the runtime configuration in sync because otherwise you are effectively lying to the compiler and all kinds of bad stuff might happen at runtime.

Example for Configuring a Custom Item Class

export class MyItem extends Item { /* ... */ }

declare global {
  interface DocumentClassConfig {
    Item: typeof MyItem;
  }
}
import { MyItem } from './item';

Hooks.once('init', () => {
  CONFIG.Item.documentClass = MyItem;
});