Sharing interfaces and classes between frontend (Angular) and backend development in TypeScript

In my current project, I have a monorepo consisting of a Frontend (Angular) and a Backend (built with NestJS, which is based on NodeJS). I am looking to implement custom interfaces and classes for both the frontend and backend. For example, creating DTOs so that the frontend understands the parameters used by the backend.

I initially considered organizing these custom interfaces and classes in a common folder within the project structure shown below. However, this approach proved to be problematic as the common folder is outside the scope of Angular's tsconfig file, leading to issues with auto-completion functionality.

project
├── client (Angular)
├── server (NestJS)
└── common (shared interfaces and classes for both client and server)

Has anyone encountered a similar situation? Currently, I am duplicating my interfaces in both folders, but this is not ideal as any updates made to one interface require manually updating the other as well.

Answer №1

If you're working with TypeScript 3.0, you may find "Project references" to be a valuable feature. I personally used it to share models between Angular and cloud functions.

Find out more about Project References here

To make use of this feature, simply add an external project reference to the tsconfig.json file of the project that needs to access files from another location:

{
  "compilerOptions": {
    // Your usual settings here
  },
  "references": [
    { "path": "../my-other-project" }
  ]
}

Answer №2

Utilizing a tool such as Lerna can simplify the setup process, making it easier to manage without having to create private npm repositories.

The basic idea is to configure your angular and server packages to include the common package like any other npm module, then use Lerna to establish virtual links between each package. This allows your editor to access these virtual file links created by Lerna during the bootstrap phase, facilitating the integration of multiple common packages with minimal effort.

Answer №3

To incorporate the 'common' module into your project, update your tsconfig.json by including it in the paths property:

     "paths": {
       "@angular/*": ["node_modules/@angular/*"],
       "rxjs/*": ["node_modules/rxjs/*"],
       "common/*": ["../common/*"]
     }

After making this change, you can import any exported interface from the common folder like this:

import myInterface from 'exported interface in common folder';

For better organization, consider creating an index.ts file that exports all services and interfaces in one place: export * from './myFile'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulties installing npm bootstrap@3 within the Angular framework

Recently, I started learning Angular and decided to integrate Bootstrap into my Angular project. However, when I entered npm install --save bootstrap@3 into the terminal, the following warning messages were displayed: C:\Users\ssc\Angular-T ...

I am experiencing difficulty with VS Code IntelliSense as it is not displaying certain classes for auto-import in my TypeScript project

I'm currently working on a project that has an entrypoint index.ts in the main folder, with all other files located in src (which are then built in dist). However, I've noticed that when I try to use autocomplete or quick fix to import existing ...

Tips for setting an argument with a promise data type

I am currently working on writing unit tests using jest to test two functions in a separate file called generator, where I generate fake data : generator.ts export async function generateReportData(overide = {}) { return { clientId: faker.data ...

The JSX component is unable to utilize the object

When working with Typescript in a react-three-fiber scene, I encountered an error that GroundLoadTextures cannot be used as a JSX component. My aim is to create a texture loader component that loads textures for use in other components. The issue arises f ...

The response type for HTTP Get in Typescript is specified as "text"

I'm currently working on a Typescript HTTP Get request and need to customize the response type as text. Here's my code snippet: getMessageContent(messageContentId?: string): Observable<string> { const url = this.commonService.getApi ...

Dynamic URL in Angular service for JSON API request

Utilizing an Angular service, I am retrieving JSON data from a specified URL. Take a look at the code snippet provided below: import { Injectable } from '@angular/core'; import {Http,Response} from "@angular/http"; import { Observable } from "rx ...

Error in Typescript/React: Unable to access the property 'MaxEmailLength' as it is undefined

I am facing an unusual problem with TypeScript. I have two static classes that are mutually referencing each other and causing issues. Class ValidationHelper (single file) import { ValidationErrors } from '../dictionary/ValidationErrors'; ex ...

Error in Angular 2 after transition to @types: encountering "require" name not found issue

After transitioning my project from old typings to types-publisher, I have successfully resolved most of my dependencies. However, I am consistently encountering an error that reads Cannot find name 'require'. Below is a snippet from my tsconfig. ...

Ways to recover information that is not typically found

My firebase database has two main trees: "tag" and "user". Each user is associated with a set of tags, referred to as preferences. Here is the structure of my database: I am trying to display a list of preferences that a specific user does not have. Exam ...

Learn the proper way to specify the return type of a function as a class, rather than an instance, in Typescript

Is there a way to declare that a function returns a generic class definition? I have tried the following for non-generic classes, but it does not work for generic ones: export function composeAll(composeFunction: Function, depsFunction: Function): (compon ...

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

Guide on successfully importing a pretrained model in Angular using TensorFlow.js

I need help with uploading a pretrained Keras model to my existing tensorflow.js model and then making simple predictions by passing tensors in the correct format. The model is stored locally within the project, in the assets folder. export class MotionAn ...

NGRX effect in Nativescript Angular loses state when the app is suspended on iOS

While using NGRX with Nativescript Angular to manage state and fetch data from the server, I've encountered an issue when suspending the app on IOS. Whenever the app is in the middle of fetching data from the server and gets suspended, the entire proc ...

Exploring the functionality of the `super()` method in TypeScript

I'm trying to enhance the standard JavaScript Error class by adding another property called code, but for some reason, TypeScript is not allowing me to do so. Here is the code snippet: export class HttpError extends Error { public message: string ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

"Exploring the power of Angular 16 coupled with Firebase 9 for seamless file

Recently, I've been facing some challenges with my Angular 16 app that uses Firebase 9 and angular/fire 7. Specifically, I've been struggling to implement a simple file upload feature to Firebase storage. Despite spending the last couple of days ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

What is the method for reaching a service in a different feature module?

Currently, I am utilizing Angular 2/4 and have organized my code into feature modules. For instance, I have a Building Module and a Client Module. https://i.stack.imgur.com/LvmkU.png The same structure applies to my Client Feature Module as well. Now, i ...

How can I upload multiple images in one request using Typescript?

HTML: <div> <input type ="file" (change)="selectFiles($event)" multiple="multiple" /> </div> Function to handle the change event selectFiles(event) { const reader = new FileReader(); if (event.target.files & ...