Manipulating documents and entries with a TypeScript-based project
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.ContentTyperepresents a union of every content-type identifier in the applicationUID.Componentrepresents a union of every component identifier in the applicationUID.Schemarepresents 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.ContentTyperepresents a Strapi document objectData.Componentrepresents a Strapi component objectData.Entityrepresents 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;
}
Generic components
function renderComponent(parent: Node, component: Data.Component) {
const elements: Element[] = [];
const properties = Object.entries(component);
for (const [name, value] of properties) {
// ^ ^
// string any
const paragraph = document.createElement('p');
paragraph.textContent = `Key: ${name}, Value: ${value}`;
elements.push(paragraph);
}
parent.append(...elements);
}
Known entities
When manipulating known entities, it is possible to parametrize Data types for better type safety and code completion.