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

Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors du ...

Each time a page loads, the react useContext feature is causing the web socket connection to reset

I have integrated websockets into various parts of my nextJS application and need to make sure they are accessible everywhere without resetting the socket connection. Whenever the connection is reset, it loses all the rooms it was connected to, causing iss ...

Facing problem with implementing NgMoudleFactoryLoader for lazy loading in Angular 8

A situation arose where I needed to lazy load a popups module outside of the regular router lazy-loading. In order to achieve this, I made the following adjustments: angular.json "architect": { "build": { ... "options": { ... "lazyM ...

How can I detect Mongoose events through syntax?

Is there a way to detect the open event in Mongoose based on their documentation located here? According to the documentation, once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is m ...

Experiencing a problem with Datatables where all columns are being grouped together in a single row

After creating a table with one row using colspan and adding my data to the next row, I encountered an issue with the datatables library. An error message appeared in the console: Uncaught TypeError: Cannot set property '_DT_CellIndex' of unde ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

What is the best way to showcase SVG code as an image using Vuejs?

My API is returning an SVG image as ASCII text code, which I am trying to display on my page. However, instead of the image, I just see a blank space. You can view my attempted solution in this JSFiddle: https://jsfiddle.net/c0p4ku78/ The key parts of th ...

What are the methods used to optimize fetching on a React Gatsby website?

Within the Gatsby React setup of a website, there is a NavbarExtra component on the front page that displays dynamic data fetched from an API. This data refreshes multiple times throughout the day. The goal now is to optimize the fetching process in order ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

Clicking on React Js reverses an array that had previously been unreversed

My issue involves an array pulled from a database that I have reversed so that the newest entry is displayed at the top when a button is clicked, opening a modal-style window. However, when the array is displayed in the modal window, it appears to be flipp ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

Tips for incorporating jQuery to load Rails form partials and submit them as a single form:

Trying to improve the readability of my Rails HTML code, I decided to extract certain portions into partials and then used jQuery to render these partials. However, a problem arose where the form seems disconnected after implementing this approach. It appe ...

Update the function to be contained in a distinct JavaScript file - incorporating AJAX, HTML, and MySQL

Currently, I am working on a project and need to showcase a table from MySQL on an HTML page. The JavaScript function in my code is responsible for this task, but due to the Framework 7 requirement, I must separate the function into a different .js file ra ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

Is it possible for the JavaScript DOM API to retrieve the exact casing of attribute and tag names?

Is it possible to retrieve the original casing of an attribute name or tag name from the source? The attribute name is in lowercase The tag name is in uppercase The local element name is in lowercase I am looking for a solution that doesn't require ...

Struggling to connect API from React and Node using a proxy server

I have encountered a troubleshooting issue with React and Node that I am struggling to resolve. The problem lies in the communication between my node server and coinmarketcap API. While I successfully receive data from both endpoints (all coins and individ ...

Interactive hover effect in JavaScript displays a larger version of other thumbnails when hovering over a dynamically loaded thumbnail image, instead of its own full-size image

I recently began teaching myself PHP and Dreamweaver with the help of a video tutorial on building data-driven websites using Dreamweaver. My goal is to create a dynamic table with 6 columns and 20 rows. column1 | column2 | column3 | colu ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

The CSS stylesheet is not being applied to the components in Next.js

I am currently facing an issue with styling my React/Next component. Despite trying to apply a stylesheet to enhance its appearance, the CSS doesn't seem to be taking effect. Could someone please provide guidance on how I can resolve this? I have att ...