strapi-schema-types
v1.0.4
Published
Typescript interface generator for Strapi 4 and 5 models
Maintainers
Readme
Strapi-Schema-Types
Typescript interface generator for Strapi 4 and 5 models.
Install locally
This project is a fork of the original types-4-strapi by Francesco Lorenzetti .
npm i --save-dev strapi-schema-typesAdd t4s to your scripts:
"scripts": {
"develop": "strapi develop",
"start": "strapi start",
"build": "strapi build",
"strapi": "strapi",
"t4s": "t4s"
}Then run with:
npm run t4s # For Strapi v4
npm run t4s -- --v5 # For Strapi v5Install globally
npm i -g strapi-schema-typesThen run with:
t4s # For Strapi v4
t4s --v5 # For Strapi v5Attributes
For Strapi v4, the resulting interfaces will look like this:
{
id: number;
attributes: {
username: string;
email: string;
provider: string;
confirmed: boolean;
blocked: boolean;
createdAt: Date;
updatedAt: Date;
}
}For Strapi v5, the resulting interfaces will look like this:
{
id: number;
documentId: string;
username: string;
email: string;
provider: string;
confirmed: boolean;
blocked: boolean;
createdAt: Date;
updatedAt: Date;
}Example Usage
For Strapi v4:
// correct
await fetch('https://project.com/api/users', {
method: 'POST',
body: JSON.stringify({
username: 'Jon Snow',
email: '[email protected]',
}),
});
// incorrect
await fetch('https://project.com/api/users', {
method: 'POST',
body: JSON.stringify({
attributes: {
username: 'Jon Snow',
email: '[email protected]',
},
}),
});For Strapi v5:
await fetch('https://project.com/api/users', {
method: 'POST',
body: JSON.stringify({
username: 'Jon Snow',
email: '[email protected]',
}),
});In these cases, rather than creating completely new types, we recommend that you simply 'extract' the type of the attribute object from the entity's interface using indexed access types.
type UserAttributes = User['attributes'];
await fetch('https://project.com/api/users', {
method: 'POST',
body: {
username: 'Jon Snow',
email: '[email protected]',
} as UserAttributes
});If you are using strapi-plugin-transformer to remove the attributes key from all responses, use the following generic transformation type to be able to utilise the interfaces generated by strapi-schema-types:
type Transformed<A extends { attributes: any }> = A['attributes'] & {
id: number;
};Usage:
const response = await fetch('https://project.com/api/users');
const json = await response.json();
const users = json.data as Transformed<User>[];For Strapi v5, the transformation type would be:
type TransformedV5<A> = Omit<A, 'id'> & {
documentId: string;
};Usage:
const response = await fetch('https://project.com/api/users');
const json = await response.json();
const users = json.data as TransformedV5<User>[];