Strapi Custom service types

System Information
  • Strapi Version: 4.3.8
  • Operating System: Win 10
  • Database: Any
  • Node Version: 16.16.0
  • NPM Version: 8.11.0
  • Yarn Version:

Hi all. I was on Strapi 4.3.2 and already had time to type my custom services. Then I saw that there is already version 4.3.8 with many fixes which I had to patch myself. I decided to update and immediately encountered problems.

  1. this problem of loading ts config is solved for now by patching the file “get-config-path.js” Typescript `@strapi/typescript-utils`'s `getConfigPath` return false negative due to incorrect directory checking procedure in Windows · Issue #14306 · strapi/strapi · GitHub
  2. I have all types broken.

All services and controllers that have an extension scream this error. I’ve read cursorily what it’s related to. It looks like typescript is getting tougher on [key: type]: any. Also Strapi introduced GenericService which is union SingleTypeService | CollectionTypeService with possibility to extend it by [method: string | number | symbol]: <T = any>(…args: any) => T;

I made a clean project to check this.

Before the upgrade, I described the service type through an interface inheriting from Collection or Single type as here. After updating it will not work and you will get an error as above.

export interface ListService extends CollectionTypeService {
  magic?(id: number): void;

After going through the options. I managed to make it work by describing the type not as an interface, but as a type with an extension from Generic.

export type ListService = GenericService & {
  magic?(id: number): void;

And you also need to explicitly type in the factory method, otherwise typescript will not be able to explicitly match them.

export default factories.createCoreService<ListService>(
  ({ strapi }) =>
      magic(id: number) {
    } as ListService)

I do not know whether to consider it a bug or I just did not find this information in the documentation or breaking changes. I would like to ask whether it is worth it to work further, because I have quite a lot of such services and I would not want to rewrite everything again in the new version. I need the typing very much.

Thanks Strapi is a great product after all.


We’re running into the same issue. Would greatly appreciate help with this.

For now, I’m still using the method I described. Type everything as a union type with GenericService and then specify the type 2 times.