Share Types between backend and frontend in a monorepo

To avoid creating duplicate Interfaces and Types in your backend and frontend for DTO´s, parameters and you name it; we can share those types with TypeScripts: Path mapping.

Add a custom path in your frontend/client-side tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": { "@backend/*": ["../server/src/types/*"], },
  }
}
  1. The path is going up a directory from your baseUrl and then going to server/src/types-directory.
  2. We add * as a wildcard to mean that everything in that directory is to be accessible.
  3. We call our path @backend. This will be used as an alias when using ES6-imports.

Types are now available to be imported from the server-side with ES6-imports:

import { ItemDTO } from "@backend/itemDTO.js"
// the relative server-side path: ./src/types/itemDTO.js

30 december 2022