The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well.

This is the scenario. When running the following code:

class Person {
    @IsValueIn(['PETER', 'JAMES'])
    @IsAlpha()
    @IsDefined()
    public name:string;
}

An error message is displayed:

Error in /turbo_modules/@fireflysemantics/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b1c7d0ddd8d5d0c5dec3f1829f819f8081">[email protected]</a>/bundles/fireflysemantics-validator.umd.js (194:21)
The ValidationContainer
already contains context with signature IsValueIn_Person_name.

However, if we comment out @IsValueIn(['PETER', 'JAMES']):

class Person {
    //@IsValueIn(['PETER', 'JAMES'])
    @IsAlpha()
    @IsDefined()
    public name:string;
}

No exceptions are raised.

Upon decorator instantiation, a function is called twice (confirmed by logging statements):

  /**
   * @param target Add a ValidationContext instance.
   * @throws Error if attempting to add a ValidationContext with a signature that duplicates that of an instance already contained.
   * 
   * If an exception thrown it indicates that a duplicate class definition exist
   * in the runtime.  In other words the same class definition is loaded more
   * than once because it exists in multiple files.
   * 
   */
  public static addValidationContext(target: ValidationContext): void {

    const key: string = getPropertyKey(
      target.target.name,
      target.propertyName
    );

    console.log("The property key is: ", key)
    console.log("The target signature is: ", target.getSignature())

The following logging statements indicate the duplication issue:

ValidationContainer.ts:69 The target signature is:  IsDefined_Person_name
ValidationContainer.ts:68 The property key is:  Person_name
ValidationContainer.ts:69 The target signature is:  IsAlpha_Person_name
ValidationContainer.ts:68 The property key is:  Person_name
ValidationContainer.ts:69 The target signature is:  IsValueIn_Person_name
ValidationContainer.ts:68 The property key is:  Person_name
ValidationContainer.ts:69 The target signature is:  IsValueIn_Person_name

It's evident that IsValueIn_Person_name is being created twice due to the double decorator instantiation, leading to the exception being raised.

Any thoughts on this?

Answer №1

It's a misconception that the decorator is being called twice based on logs.

In the current source code:

export function IsValueIn(target: any[], validationOptions?: ValidationOptions) {

  const validationParameters:any[] = [];
  validationParameters.push(target);

  return function(object: any, propertyName: string) {
    const vc: ValidationContext = new ValidationContext(
      object,
      object.constructor,
      IsValueIn.name,
      propertyName,
      validateValue,
      null,
      true,
      errorMessage,
      validationOptions
    );
    ValidationContainer.addValidationContext(vc);
    ValidationContainer.addValidationContext(vc);
  };
}

The line

ValidationContainer.addValidationContext(vc);
is responsible for the double logs being produced.

To eliminate this issue, simply remove line 33 or 34 ;)

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

Refresh the block's content seamlessly without the need for a page reload

Within the index.html page There exists a block called content that contains various content blocks. An additional navigation menu with numerous links is present. It is important that when you click on a menu link, the content within the content block re ...

Injecting data into a Q promise

I'm facing some issues related to what seems like JavaScript closures. In my Express + Mongoose web application, I am utilizing the Q library for Promises. I have a question regarding passing request data to the promise chain in order to successfully ...

I'm encountering an issue with one of my routes not loading correctly in Angular 4 Universal

I have been working on implementing Universal and I believe I've made significant progress. My project is built on this seed. However, when I run "npm start", only the /about and /contact pages render successfully. The /home page does not render at al ...

Using React hooks to update the state of an array from one component to another

I am currently working on a MERN blog website project and I've encountered an issue while trying to update comments on a post. I'm editing the comment from another component but facing difficulty in updating the state after making changes. Would ...

The ReactJS code encountered an error when attempting to access the 'location' property of an undefined or null reference

My Reactapp is encountering an error due to a specific file. import React from 'react'; import { Router, Route } from 'react-router'; import App from './components/App'; import About from './components/About'; im ...

Leveraging a combination of AngularJS directives within a single div element

Why can't I use multiple directives in the same div tag in AngularJS? The product names from the module are not displayed with the following HTML code: <!DOCTYPE html> <html ng-app="gemStore"> <head> <title></ti ...

Sending data to a parent component from a popup window in Angular Material using a button click while the window is still open

How can I retrieve data from an Angular Material Dialog Box and send it to the Parent component? I am able to access data after the dialog box is closed. However, I am wondering if there is a way to retrieve data while the dialog box is still open, especi ...

componentWillReceiveProps with excessive conditional statements

Having recently ventured into React development, I've already worked on 3 major projects utilizing React+Redux. However, I've noticed a recurring pattern that I find quite displeasing: componentWillReceiveProps(nextProps) { if (nextProps.par ...

Tips for implementing the data.map function in Reactjs

I am currently exploring Reactjs with nextjs, and I am facing an issue with fetching data using the "map" function. Can anyone provide guidance on how to approach this? Below is my current code snippet: import { useEffect, useState } from "react" export ...

Step-by-Step Guide on Dividing Table Row Data into Two Distinct Tables

At present, I have created a dynamic table that retrieves data from the database using forms in Django. I'm facing an issue with this table as even though there are 7 columns, only 2 of them are visible. However, all 5 hidden columns do contain impor ...

Populate input fields in HTML using Angular 4

Within my angular 4 project, I am facing the challenge of setting a value in an input field and in a MatSelect without relying on any binding. Here is the HTML structure: <div class="row search-component"> <div class="col-md-5 no-padding-rig ...

Can a local image be incorporated into an HTML or CSS project through the use of Javascript or alternative methods?

I've been trying, but all I can manage is: <img width='220' height='280' src='chrome-extension://okjaohhbffepkcfacapapdhkmnebgiba/johnny.jpg' class="me"/> Unfortunately, this code only works in Chrome. Is there a ...

Effective strategies for integrating Bootstrap and AngularJS without relying on jQuery

Currently exploring AngularJS after experimenting with Twitter's Bootstrap. I appreciate Bootstrap for its simplicity, sleek design, and mobile-friendliness. On the other hand, I have noticed a trend where people recommend using AngularJS over jQuery, ...

Maximizing CSS opacity for optimal performance in image fading

I'm working on creating a smooth fade in-out effect for the images in my photo gallery by adjusting the CSS opacity value using JavaScript. However, I've noticed that this process is quite sluggish on certain computers, such as my relatively new ...

What is the proper way to declare a JavaScript variable using a hyphen symbol?

When it comes to evaluating a string like employee-count = 3, my main issue arises when dealing with variables that may not have a standard naming convention. While valid variable names pose no challenge, identifiers such as employee-count leave me slightl ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Modifying the $locale setting in ui-router

My Goal and Approach Within our AngularJS application, we utilize angular-ui-bootstrap for datepickers. Our aim is to localize the datepickers based on the user's locale. However, dynamically changing the locale in AngularJS poses a challenge due to ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...