Enhancing Typescript Arrow Function Parameters using Decorators

Can decorators be used on parameters within an arrow function at this time? For instance:

const func: Function = (@Decorator param: any) => { ... }

or

class SomeClass {
  public classProp: Function = (@Decorator param: any) => { ... }
}

Neither WebStorm nor the compiler seems to support it, and there doesn't appear to be any documentation online indicating if this is acceptable in TypeScript.

I'm specifically facing issues when trying to use it within a class as a property, but it seems like this problem also applies to regular variable declarations.

If this syntax isn't currently valid, are there any plans to permit it in the future?

Answer №1

If you are looking for information in the typescript documentation, your answer can be found here: https://www.typescriptlang.org/docs/handbook/decorators.html

To summarize the relevant part:

import "reflect-metadata";

const requiredMetadataKey = Symbol("required");

function required(target: Object, propertyKey: string | symbol, parameterIndex: number) {
    let existingRequiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyKey) || [];
    existingRequiredParameters.push(parameterIndex);
    Reflect.defineMetadata(requiredMetadataKey, existingRequiredParameters, target, propertyKey);
}

function validate(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>) {
    let method = descriptor.value;
    descriptor.value = function () {
        let requiredParameters: number[] = Reflect.getOwnMetadata(requiredMetadataKey, target, propertyName);
        if (requiredParameters) {
            for (let parameterIndex of requiredParameters) {
                if (parameterIndex >= arguments.length || arguments[parameterIndex] === undefined) {
                    throw new Error("Missing required argument.");
                }
            }
        }

        return method.apply(this, arguments);
    }
}

You can use it like this:

class Greeter { greeting: string;

   constructor(message: string) {
       this.greeting = message;
   }

   @validate
   greet(@required name: string) {
       return "Hello " + name + ", " + this.greeting;
   }

I hope this is helpful :)

Seb

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

What sets TypeScript apart from AtScript?

From what I understand, TypeScript was created by Microsoft and is used to dynamically generate JavaScript. I'm curious about the distinctions between TypeScript and AtScript. Which one would be more beneficial for a JavaScript developer to learn? ...

What is the reason TypeScript does not recognize the type when dealing with promises?

I am encountering an unexpected behavior where there is no error even though there should be one in TypeScript when using promises. I assigned a number value to a string variable, but surprisingly, no error was thrown. Why does this happen? https://codesa ...

Starting up a pre-existing Angular project on your local machine

I am completely new to Angular and facing difficulties running an existing project on my machine. Despite conducting numerous tests and following various articles, I still cannot get the project to run. Here is the layout of my project files: https://i.s ...

Creating an interactive element in Angular: A step-by-step guide

Hey there, I'm facing a problem with creating a specific payload structure as shown in the example code snippet below. Everything was going well until I got stuck at the dynamic form part, and despite several attempts, I can't seem to figure it o ...

Generating a date without including the time

I recently started working with React (Typescript) and I am trying to display a date from the database without including the time. Here is my Interface: interface Games { g_Id: number; g_Title: string; g_Genre: string; g_Plattform: string; g_ReleaseDate: ...

How to extract multiple literals from a string using Typescript

type Extracted<T> = T extends `${string}${'*('}${infer A}${')+'}${string}${'*('}${infer A}${')+'}${string}` ? A : never type Result1 = Extracted<'g*(a12)+gggggg*(h23)+'> // 'a12' | &a ...

Blob is unable to open the PDF file as it is not

Currently, I am utilizing ASP.NET Core and Angular to create a web application. In one of the controller actions, I am returning a File like this: return Ok(Microsoft.AspNetCore.Mvc.File(await GetFileContents(args), "application/pdf")); Then in TypeScript ...

Setting style based on the condition of the router URL

I am currently facing an issue with a global script in Angular 10 that is supposed to evaluate the current path and apply a style to the navigation bar conditionally. However, it seems to fail at times when using router links. I am wondering if there is a ...

Tips for formatting dates in Angular 6

I am currently working on a function that displays real-time dates based on user input. Currently, when the user enters the input, it is displayed in the front end as follows: 28.10.2018 10:09 However, I would like the date to change dynamically based on ...

The call stack size has been exceeded in Next.js, resulting in a RangeError

Currently attempting to deploy my project on vercel.com but encountering an error specifically with 3 pages that have no internal errors. An error occurred while prerendering the page "/applications". For more information, visit: https://nextjs.org/docs/me ...

A step-by-step guide on enhancing error message handling for Reactive forms in Angular

Here is a code snippet that I'm working on: public errorMessages; ngOnInit(): void { this.startErrorMessage(); } private startErrorMessage() { this.errorMessages = maxLength: this.translate.instant(' ...

Mastering the art of leveraging generics in conjunction with ngrx actions

Currently, I am in the process of developing an Angular 7 application that utilizes the NGRX store. In our application, we have numerous entities, each with its own dedicated list view. I decided to explore using generics with the NGRX store to avoid writi ...

Creating a sidebar in Jupyter Lab for enhanced development features

Hi there! Recently, I've been working on putting together a custom sidebar. During my research, I stumbled upon the code snippet below which supposedly helps in creating a simple sidebar. Unfortunately, I am facing some issues with it and would greatl ...

Leveraging Services in Classes Outside of Angular's Scope

I have a scenario where I am working with Angular v7.3.5 and I need to utilize a Service in a non-Angular class. Below is an example of what I'm trying to achieve: foo.model.ts import { Foo2Service } from './foo2.service'; // Definition fo ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

A declaration file for the 'vuelidate' module could not be located

When I was following the installation instructions for Vuelidate in Vuejs (), I encountered a warning message at this line: import Vuelidate from 'vuelidate' The warning states: There seems to be an issue with finding a declaration file for t ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Using jest to simulate a private variable in your code

I am working on unit testing a function that looks like this: export class newClass { private service: ServiceToMock; constructor () { this.service = new ServiceToMock() } callToTest () { this.service.externalCall().then(()=& ...

Is it advisable for a component to handle the states of its sub-components within the ngrx/store framework?

I am currently grappling with the best strategy for managing state in my application. Specifically, whether it makes sense for the parent component to handle the state for two subcomponents. For instance: <div> <subcomponent-one> *ngIf=&qu ...