DEV Community

loading...
Cover image for How do you unify TypeScript for both frontend and backend?

How do you unify TypeScript for both frontend and backend?

patarapolw profile image Pacharapol Withayasakpunt ・1 min read

As far as I know, there are only handful of frameworks doing this, e.g. blitz.js and frourio.

However, I know another easy way - Swagger/OpenAPI + typegen + Nodemon.

// nodemon.json
{
  "restartable": "rs",
  "execMap": {
    "ts": "yarn ts"
  },
  "events": {
    "restart": "yarn openapi || :"
  },
  "watch": [
    "server/"
  ],
  "env": {
    "NODE_ENV": "development"
  },
  "ext": "ts"
}
Enter fullscreen mode Exit fullscreen mode
// package.json
{
  "scripts": {
    "openapi": "wait-on tcp:$SERVER_PORT && curl -s http://localhost:$SERVER_PORT/api/doc/json -o ./assets/openapi.json && typegen ./assets/openapi.json > ./types/openapi.d.ts",
    "ts": "ts-node -r tsconfig-paths/register -O '{\"module\":\"commonjs\",\"noImplicitAny\":false}'"
  }
}
Enter fullscreen mode Exit fullscreen mode

And typegen is openapi-client-axios-typegen. (You can also try swaxios, but I failed to run it.)

With this approach, backend can be any programming languages that support OpenAPI or Swagger. Personally, I use fastify-swagger; but it can also be things like Python's FastAPI or Golang's Gin/Buffalo/Native.

Discussion (0)

pic
Editor guide