Typescript in payload CMS

Payload supports TypeScript natively, and not only that, the entirety of the CMS is built with TypeScript. To get started developing with Payload and TypeScript, you can use one of Payload’s built-in boilerplates in one line via create-payload-app

npx create-payload-app@latest

Payload exports a number of types that you may find useful while writing your own plugins, hooks, access control functions, custom views, GraphQL queries / mutations, or anything else.

Run the following command in a Payload project to generate types based on your Payload config:

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

If you are using your payload-types.ts file in other repos, though, it might be better to disable this declare statement, so that you don’t get any TS errors in projects that use your Payload types, but do not have Payload installed.

// payload.config.ts

2{

3 // …

4 typescript: {

5 declare: false, // defaults to true if not set

6 },

7}

If you do disable the declare pattern, you’ll need to manually add a declare statement to your code in order for Payload types to be recognized. Here’s an example showing how to declare your types in your payload.config.ts file:

// payload.config.ts

2{

3 // …

4 typescript: {

5 // defaults to: path.resolve(__dirname, ‘./payload-types.ts’)

6 outputFile: path.resolve(__dirname, ‘./generated-types.ts’),

7 },

8}

Leave a comment

Your email address will not be published. Required fields are marked *