Error: [*] is inaccessible prior to initialization. Implementing nested object validation using Class-validator in NestJs

I'm really struggling to grasp what's happening here and where I might be going wrong. I've searched through similar threads, but none seem to address my specific issue (most discussions revolve around validating typed Arrays).

Let me present the class that I am trying to validate:


export class CreateActivityDto {
   
    //other properties that are not causing any issues

    @IsArray()
    @ValidateNested({ each: true })
    @Type(() => Plan)  
    plan: Plan[]  //this part is functioning correctly
    

    @IsObject()
    @IsDefined()
    @Type(() => Location) //imported from class-transformer
    location: Location
}
class Location {
    @IsString()
    @IsNotEmpty()
    address: string
    @IsObject()
    @Type(() => LatLng) //imported from class-transformer
    coords: LatLng
}

class LatLng {
    @IsNumber()
    lng: number
    @IsNumber()
    lat: number
}

Oddly enough, if I declare location as an array of locations (location: Location[]), the error doesn't occur.

I encounter this error during runtime, just a few milliseconds after the server attempts to bootstrap:

[6:25:19 pm] Found 0 errors. Watching for file changes.

[fullDirHere]\src\activity\dtos\activity.dto.ts:52
location: Location
              ^
ReferenceError: Cannot access 'Location' before initialization

And here is a snippet from my main.ts file:

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    transform: true,
    transformOptions: {
      enableImplicitConversion: true
    }
  }))
  await app.listen(3000);
}
bootstrap();

Just to provide clarity, here is an example of a valid object that I could potentially receive:

{
"location": {
          "address": "Av. Corrientes 2003, Buenos Aires, Argentina",
          "coords": {
                    "lat": -34.6042967,
                    "lng": -58.39546360000001
               },
...other properties...
}

Answer №1

To resolve the issue, simply rearrange the order in which these classes are declared. I have personally tested this and it worked correctly on my local environment:


class LatLng {
    @IsNumber()
    lng: number;
    @IsNumber()
    lat: number;
}

class Location {
    @IsString()
    @IsNotEmpty()
    address: string;
    @IsObject()
    @Type(() => LatLng) //imported from class-transformer
    coords: LatLng;
}
export class CreateActivityDto {
    // other validated properties that are working fine

    @IsArray()
    @ValidateNested({ each: true })
    @Type(() => Plan)
    plan: Plan[]  // no issues with this property

    @IsObject()
    @IsDefined()
    @Type(() => Location) // imported from class-transformer
    location: Location;
}

Keep in mind that decorators typically run before other code snippets.

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

Utilizing TypeORM's distinctOn function in conjunction with orderBy

Looking to retrieve the latest message for a user, whether they are the sender or the receiver. Unfortunately, I'm unable to utilize distinctOn along with orderBy const query = this.createQueryBuilder('message') .orderBy(& ...

Issue encountered: Unable to access the property 'loadChildren' as it is undefined, while attempting to configure the path

How can I conditionally load the route path? I've attempted the code below, but it's throwing an error. Can someone guide me on how to accomplish this task? [ng] ERROR in Cannot read property 'loadChildren' of undefined [ng] i 「w ...

Stop webpack from stripping out the crypto module in the nodejs API

Working on a node-js API within an nx workspace, I encountered a challenge with using the core crypto node-js module. It seems like webpack might be stripping it out. The code snippet causing the issue is: crypto.getRandomValues(new Uint32Array(1))[0].toS ...

Using *ngIf with values from an array in *ngFor in Angular 2: How to make it work?

i just started learning angular 2 and ionic, so I'll keep it brief: <ion-card class="acc-page-card" *ngFor="let account of accounts"> <ion-card-content> <!-- Add card content here! --> <ion-item (click)="GoTo('Ac ...

Combining marker, circle, and polygon layers within an Angular 5 environment

I am working on a project where I have an array of places that are being displayed in both a table and a map. Each element in the table is represented by a marker, and either a circle or polygon. When an element is selected from the table, the marker icon ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

Verify the data types of components received as props in a Typescript React application

I have a question regarding type checking in React components passed as props: What is the method for ensuring that only allowed components are passed as props? Allow me to demonstrate. We have the component we wish to pass around: type CustomProps = { ...

Surprising Outcome when Dealing with Instance Type - Allowing extra properties that are not explicitly stated in the type

I've come across an issue with the InstanceType Utility Type. I am trying to create a function that takes a class constructor and an instance of that class. For instance: export type Class<T=any> = { new(...args: any[]): T; }; function acceptC ...

Finding the current URL in React Router can be achieved by using specific methods and properties provided by

Currently, I'm diving into the world of react-redux with react-router. On one of my pages, it's crucial to know which page the user clicked on to be directed to this new page. Is there a method within react-router that allows me to access inform ...

Expanding the capabilities of generic functions in TypeScript using type variables

When working with generics in TypeScript, it is often beneficial for a function that accepts generically-typed arguments to have knowledge of the type. There exists a standard approach to achieve this using named functions: interface TestInterface<T> ...

Creating an array in TypeScript is a versatile and powerful feature that

While I have some familiarity with TypeScript, there is one thing that continues to intrigue me. I understand the distinction between Array<string> and string[]. I am aware that these declarations can be used interchangeably, such as: export class S ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

``There are problems with parsing JSON data due to the error message indicating the presence of unexpected

I am encountering an issue with displaying values from objects stored as string[] in appwriteDB. When trying to use *ngFor to iterate through the data, I faced difficulties. Despite attempting to convert the orderItems using JSON.parse(), the process faile ...

Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript? public shops: string[] = [ "AShop", "BShop", "CShop", ]; this.shops.forEach((shop, index) => { let instance = new window[shop](index ...

The package.json entry for "abc-domains" is not functioning correctly even though it is set to "latest" version

Unique Scenario Imagine there's a package called xyz-modules that I've developed. The package.json file in my project looks like this: ... "devDependencies": { "@company/xyz-modules": "latest", ... } ... After ...

When I attempt to map imports in Typescript, an error occurs, stating, "Element implicitly has an 'any' type because the expression of type 'string' is being indexed into type 'typeof import'."

(parameter) key: string An issue arises where the expression of type 'string' cannot be used to index type 'typeof import("d:/Projects/Front/attendance-checker2/src/redux/modules/sagas")', leading to an implicit 'any&a ...

Issue reported: "Usage of variable 'someVar' before assignment" ; however, it is being properly assigned before usage

This piece of code showcases the issue: let someVar: number; const someFunc = async () => { someVar = 1; } await someFunc(); if (someVar == 1) { console.log('It is 1'); } As a result, you will encounter ...

What is the best way to include a non-Typed Angular service in a TypeScript class?

I have a module and service in Angular that were originally developed without TypeScript, like this: MyModule = angular.module('MyModule', ['dependency1', 'dependency2']); MyModule.factory('MyService', ['$other ...

Construct this node project utilizing either gulp or webpack exclusively

In the structure of my project, you will find various folders like node, build, gulp, and src. These folders contain important files for the development process such as .gitignore, gulpfile.js, package.json, tsconfig.json, webpack.config.js, server.js, con ...

Is it better to set Angular2 @Inputs as public, or should we opt for a stricter API by keeping them private?

I am currently utilizing Angular2 with Typescript Imagine having the following code in the template of my app component: ... <coffee-cup [coffee]="" ... Here is my coffee-cup component: @Component({ selector: 'coffee-cup', ... }) ex ...