Strapi 4 - How does Strapi define the property types of custom api's?

System Information
  • Strapi Version: 4.20.1
  • Operating System: MacOS
  • Database: -
  • Node Version: 20.10.0
  • NPM Version: -
  • Yarn Version: 1.22.21

I have migrated a custom api from an old project, to this new Typescript based project. In this process I am running into an issue that I can’t figure out how to resolve. It is related to some code in one of my controllers.

marvin-chat/controllers/create.ts

(...)
ctx.request.body.data.subject = subject
ctx.request.body.data.model = model
ctx.request.body.data.chatlog = chatlog

const result = await strapi.entityService.update('api::marvin-chat.marvin-chat', newChat.id, { 
        data:{
            identity: ctx.request.body.data.identity,
            model,
            subject,
            chatlog,
        }
});

Typescript error

Type '{
    identity: any; 
    model: string;
    subject: string;
    chatlog: { role: string; content: any; }[]; 
}' is not assignable to type 'Partial<Input<"api::marvin-chat.marvin-chat">>'.

Object literal may only specify known properties, and 'identity' does not exist in type 'Partial<Input<"api::marvin-chat.marvin-chat">>'.
    78 |         const result = await strapi.entityService.update('api::marvin-chat.marvin-chat', newChat.id, {
    79 |             data:{
  > 80 |                 identity,
       |                 ^^^^^^^^
    81 |                 model,
    82 |                 subject,
    83 |                 chatlog,

I understand the error, but I don’t understand how Strapi defines this type? I can only find the schema.json, where all 4 properties are being declared, but I understand that this is meant for the configuration within the CMS, not for the type declaration of TS. But can’t figure out which section does is responsible for this.

I was able to resolve this via the following two-step process. First I declared the object as unknown

        data:{
            identity: ctx.request.body.data.identity,
            model,
            subject,
            chatlog,
        }
} as unknown);

This allowed me to run yarn strapi ts:generate-types --debug. I also disabled a package that was causing other issues, this might also have been the reason why I couldn’t run this command before. So perhaps setting the object to unknown was not required. Either way, the problem is resolved.

Still don’t know exactly how the types are being declared, but strapi ts:generate-types seems to do the magic

1 Like