What's the best practice to develop the /api in typescript?

Hi,

This medium post explains how to port your strapi api/**/*.js files to be api/**/*.ts files.

My question here is if this is the current best practice, because:

  1. There may have been changes from version 3.0.0-beta.16.3 to now
  2. I know that there’s discussion around adding ts or flow support, so I’d like to do this with future-proofing in mind (as much as possible)

Any recommendations or acknowledgment that that is the best current way?

2 Likes

That article looks quite involved with a lot of moving parts, which puts me off a bit. To my knowledge it is the most complete example TS integration with Strapi.

For me, using the checkJs option of TypeScript has been good enough. I have this tsconfig.json at my project root:

{
  "compilerOptions": {
    "noEmit": true,
    "checkJs": true,
    "allowJs": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "**/*"
  ]
}

VSCode shows type warnings, and I can run tsc in my CI pipeline.

I can use types like this in regular JS files:

/**
 * @param {number} tagId
 * @param {number[]} fileIds
 */
async setTagFiles(tagId, fileIds) {

  /** @type {Partial<TagModel>} */
  const tagUpdate = {
    files: fileIds,
    fileCount: fileIds.length,
  };

  await strapi.api.tag.services.tag.update({ id: tagId }, tagUpdate);
},

I maintain a file of types I care about in a .d.ts file. This package would be useful but I haven’t needed it so far.

The strapi api itself is not typed at all, which would be handy. It’s possible to create a package on DefinitelyTyped but it hasn’t been done yet.

1 Like

Thanks!

I guess we’ll wait for a package on DefinetlyTyped, as you mentioned.