Declaring Collection Types in Payload

import { CollectionConfig } from “payload/types”;

export type User = {

 id: string;

 name: string;

 email: string;

 role: “admin” | “editor” | “user”; // Enum type for roles

 createdAt: string;

 updatedAt: string;

};

const Users: CollectionConfig = {

 slug: “users”,

 fields: [

  {

   name: “name”,

   type: “text”,

   required: true,

  },

  {

   name: “email”,

   type: “email”,

   required: true,

   unique: true,

  },

  {

   name: “role”,

   type: “select”,

   options: [“admin”, “editor”, “user”], // Matches the enum type

   required: true,

  },

 ],

};

export default Users;

here, we define a User type and ensure it aligns with the Payload collection schema.

The role field uses TypeScript enums to enforce valid values.

Using Payload Types in API Calls

You should use the defined types when making API calls.

Fetching Users with Type Safety

import payload from “payload”;

import { User } from “../types”; // Import the User type

const fetchUsers = async (): Promise<User[]> => {

 const users = await payload.find({

  collection: “users”,

 });

 return users.docs as User[]; // Type assertion

};

Leave a comment

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