Encountering TS1240 Error When Implementing TypeScript Property Decorators in Code Execution

I'm in the midst of a TypeScript project where I am utilizing property decorators to impose validation on class properties. Below is a simplified version of the code I am working with:

Please note: Experimental decorators are enabled for this project.

interface ValidatorConfig {
  [property: string]: {
    [validatableProp: string]: string[]; // ['required', 'positive']
  };
}

const registeredValidators: ValidatorConfig = {};

function Required(target: any, propName: string) { 
  registeredValidators[target.constructor.name] = {
    [propName]: ['required']
  };
}

function PositiveNumber(target: any, propName: string) {
  registeredValidators[target.constructor.name] = {
    [propName]: ['positive']
  };
}

function validate(obj: any): boolean {
  const objValidatorConfig = registeredValidators[obj.constructor.name];
  if (!objValidatorConfig) {
    return true;
  }

  let isValid = true;

  for (const prop in objValidatorConfig) {
    for (const validator of objValidatorConfig[prop]) {
      switch (validator) {
        case 'required':
          isValid = isValid && !!obj[prop];
          break;
        case 'positive':
          isValid = isValid && obj[prop] > 0;
          break;
      }
    }
  }
  return isValid;
}

class Course {
  @Required
  title: string;

  @PositiveNumber
  price: number;

  constructor(t: string, p: number) {
    this.title = t;
    this.price = p;
  }
}

const createCourse = new Course("Hello Book", 1000);

if (!validate(createCourse)) {
  alert('Invalid input, try again');
}

However, upon compiling my code using 'tsc app.ts', I encounter the following errors:

app.ts:57:4 - error TS1240: Unable to resolve signature of property decorator when called as an expression.
Argument of type 'ClassFieldDecoratorContext<Course, string> & { name: "title"; private: false; static: false; }' is not assignable to parameter of type 'string'.

57 @Required ~~~~~~~~

app.ts:59:4 - error TS1240: Unable to resolve signature of property decorator when called as an expression.
Argument of type 'ClassFieldDecoratorContext<Course, number> & { name: "price"; private: false; static: false; }' is not assignable to parameter of type 'string'.

59 @PositiveNumber ~~~~~~~~~~~~~~

How can I address the TS1240 errors associated with my property decorators?

Answer №1

According to the documentation...

Decorators are still not fully integrated into the JavaScript specification

To use decorators, make sure to turn on the experimentalDecorators setting in your tsconfig.json.

If you visit this TSPlayground, you'll see that your code functions properly. However, if you disable the experimentalDecorators option, it will result in the errors mentioned earlier.

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

Is it possible for me to create a data type representing "potentially undefined strings"?

Just a heads up: I have enabled --strictNullChecks Here is a function I have: export function ensure<T, F extends T>(maybe: T | undefined, fallback: F): T { if (isDefined<T>(maybe)) { return maybe } if (fallback === undefined) { ...

An error was encountered at line 52 in the book-list component: TypeError - The 'books' properties are undefined. This project was built using Angular

After attempting several methods, I am struggling to display the books in the desired format. My objective is to showcase products within a specific category, such as: http://localhost:4200/books/category/1. Initially, it worked without specifying a catego ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Creating personalized properties for a Leaflet marker using Typescript

Is there a way to add a unique custom property to each marker on the map? When attempting the code below, an error is triggered: The error "Property 'myCustomID' does not exist on type '(latlng: LatLngExpression, options?: MarkerOptions) ...

What type of value does a `use` directive return?

Upon reviewing the svelte tutorial, I observed that the clickOutside function provides an object with a destroy method. What should be the precise return type of a custom use directive? export function clickOutside(node: HTMLElement): ??? { // Initia ...

The method of having two consecutive subscribe calls in Angular2 Http

Can the Subscribe method be called twice? I am attempting to create an API factory that stores data in the factory and allows different components to use that data for each AJAX call. The factory: export class api { result = []; constructor (p ...

The Power of TypeScript's Union Types

Provided: Reducer only accepts one of the following actions: interface ItemAction { type: 'ADD_TODO'|'DELETE_TODO'|'TOGGLE_TODO', id: number } interface QueryAction { type: 'SET_QUERY', query: string ...

What is the correct way to utilize window.scrollY effectively in my code?

Is it possible to have a fixed header that only appears when the user scrolls up, instead of being fixed at the top by default? I've tried using the "fixed" property but it ends up blocking the white stick at the top. Adjusting the z-index doesn&apos ...

Exploring the world of TypeScript interfaces and their uses with dynamic keys

I am hopeful that this can be achieved. The requirement is quite simple - I have 2 different types. type Numbers: Number[]; type Name: string; Let's assume they are representing data retrieved from somewhere: // the first provider sends data in th ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

What is the process of generating an instance from a generic type in TypeScript?

Managing data in local storage and making remote API queries are two crucial aspects of my service. When defining a data model, I specify whether it should utilize local storage or the remote API. Currently, I am working on creating a proxy service that c ...

complete() method is not triggered by Observable

Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables. In my Angular application, I have developed a timer with a start button, a ...

Sending SMS from an Angular application to mobile devices can be achieved through several methods

Does anyone have experience sending SMS from an Angular6 web application? I would appreciate any guidance, such as reference links or code samples. Thank you! ...

Merge two functions that are alike into a single function

I am faced with a challenge of combining two similar functions that have some minor differences: private filterByOperationType() { let operationBuffer: IProductOperation[] = []; if (this.filterConditions[0].selected.length > 0) { operation ...

Is there a comparable feature in Typescript similar to Java/.NET Reflection? Alternatively, how can I retrieve a list of classes that inherit from a specific abstract class?

People call me Noah. // CreaturesBase: installed through 'npm install creatures-base' export default abstract class Animal {...} We have this abstract base class called Animal, which comes from a third-party package on npm. Other packages exten ...

When attempting to access the .nativeElement of an input using @ViewChild, the result is 'undefined' rather than the expected value

In my angular2 project, I created a form with the following code: import {Component, ElementRef, ViewChild, AfterViewInit} from "angular2/core"; import {Observable} from "rxjs/Rx"; import {ControlGroup, Control, Validators, FormBuilder} from "angular2/com ...

What's the best way to reset the `react-google-recaptcha` checkbox in a redux application following the submission of a form?

My Redux application consists of two files: LoginForm (which contains the form elements) and LoginFormContainer (which manages form values using Formik). I am facing an issue with resetting the captcha, as the ref is located in the LoginForm file. I attemp ...

The debate between using a Class and an Object Literal comes down to the immut

Is it possible to create read-only properties in object literals? export const Page = { email: 'input[type=email]', password: 'input[type=password]', fillLoginCredentials() { cy.get(this.email).type('email&a ...

Detect errors in the `valueChanges` subscription of Firestore and attempt a retry if an error occurs

My Angular app utilizes Firestore for storing data. I have a service set up to retrieve data in the following way: fetchCollectionColors(name) { this.db.collectionGroup('collection-colors', ref => ref.where('product', '==&ap ...