While building your own custom functionality into Payload, like plugins, hooks, access control functions, custom routes, GraphQL queries / mutations, or anything else, you may benefit from generating your own TypeScript types dynamically from your Payload config itself.
Run the following command in a Payload project to generate types:
You can run this command whenever you need to regenerate your types, and then you can use these types in your Payload code directly.
For example, let's look at the following simple Payload config:
By generating types, we'll end up with a file containing the following two TypeScript interfaces:
In order for Payload to properly infer these types when using local operations, you'll need to alias the following in your tsconfig.json file:
You can specify where you want your types to be generated by adding a property to your Payload config:
The above example places your types next to your Payload config itself as the file
generated-types.ts. By default, the file will be output to your current working directory as
Payload will automatically try and locate your config, but might not always be able to find it. For example, if you are working in a
/src directory or similar, you need to tell Payload where to find your config manually by using an environment variable. If this applies to you, you can create an NPM script to make generating your types easier.
To add an NPM script to generate your types and show Payload where to find your config, open your
package.json and update the
scripts property to the following:
Now you can run
yarn generate:types to easily generate your types.