We've been working hard at making Payload + TypeScript a match made in heaven, and with its newest version (0.13.6
), building in TypeScript just got a lot better. Most notably, we've shipped a new command that allows you to generate TypeScript types automatically from all your Global and Collection configs:
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 an example of how powerful this is, let's look at the following example config:
By generating types, we'll end up with a file containing the following two TypeScript interfaces:
All of your fields are automatically converted into their TypeScript equivalent properties. Even relationship
fields are typed properly and will reference your other collection interfaces accurately.
Specifying where you want your types to be generated is easy. Just add 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-types.ts
.
By providing the types to your hook, access control and validation functions your code editor can now give you typeahead suggestions. Writing code with autocompletion from TypeScript vastly improves the developer experience.
To demonstrate some of the new TypeScript functionality that Payload offers, let's build a way to automatically set the author
of a Posts
collection to the currently logged-in user if no author is manually set.
Here is an example of a Field hook for the author
field of the above Posts
collection:
There is a lot of power with Payload's new functionality, and we hope you're excited! We'd also love to know what you think. Stop by our GitHub Discussions board to join in on the conversations and help shape the future of Payload.
Complete information on generating types can be viewed in our documentation.
In addition to the TypeScript updates and improvements we've mentioned in this post, our Roadmap features a few more features and updates that will further solidify Payload as the most advanced and feature-packed headless CMS available.
Next up: Revisions, Autosave, Drafts, and loading UI improvements! Keep an eye out!