Manipulating documents and entries
This guide will explore TypeScript patterns for manipulating documents and entries in a Strapi v5 application, including how to leverage Strapi's UID
and Data
namespaces to interact with both generic and known entity types safely. If you're working on a TypeScript-based Strapi project, mastering these approaches will help you take full advantage of type safety and code completion, ensuring robust, error-free interactions with your application’s content and components.
- Strapi Application: A Strapi v5 application. If you don't have one, follow the documentation to get started.
- TypeScript: Ensure TypeScript is set up in your Strapi project. You can follow Strapi's official guide on configuring TypeScript.
- Generated Types: Application types have been generated and are accessible.
Type Imports​
The UID
namespace contains literal unions representing the available resources in the application.
import type { UID } from '@strapi/strapi';
UID.ContentType
represents a union of every content-type identifier in the applicationUID.Component
represents a union of every component identifier in the applicationUID.Schema
represents a union of every schema (content-type or component) identifier in the application- And others...
Strapi provides a Data
namespace containing several built-in types for entity representation.
import type { Data } from '@strapi/strapi';
Data.ContentType
represents a Strapi document objectData.Component
represents a Strapi component objectData.Entity
represents either a document or a component
Both the entities' type definitions and UIDs are based on the generated schema types for your application.
In case of a mismatch or error, you can always regenerate the types.
Usage​
Generic entities​
When dealing with generic data, it is recommended to use non-parametrized forms of the Data
types.
Generic documents​
async function save(name: string, document: Data.ContentType) {
await writeCSV(name, document);
// ^ {
// id: Data.ID;
// documentId: string;
// createdAt?: DateTimeValue;
// updatedAt?: DateTimeValue;
// publishedAt?: DateTimeValue;
// ...
// }
}
In the preceding example, the resolved properties for document
are those common to every content-type.
Other properties have to be checked manually using type guards.
if ('my_prop' in document) {
return document.my_prop;
}