Anatoly
Anatoly

Reputation: 5243

Is it possible to use TypeScripts decorator to validate value of method parameters?

I try to follow this manual TypeScript parameter decorators but struggle to get it out is it possible to create the decorator to validate the method parameter as following:

class World{
   constructor(){
   }

   sayHelloTo(@checkIfNameBeginsWithCapital name: string){
      console.log("Hello World!");
   }
}

If I understood correctly it can be achieved by creating two decorators, as following:

class World{
   constructor(){
   }

   @validate
   sayHelloTo(@nameBeginWithCapital name: string){
      console.log("Hello World!");
   }
}

@nameBeginWithCapital will define metadata on a parameter and @validate will look for the parameter with such metadata and perform actual validation, am I right?

The question do I understand correctly and if not, can @checkIfNameBeginsWithCapital be created to perform this task without additional decorators within current TS limitations?

Upvotes: 2

Views: 2105

Answers (1)

pascalpuetz
pascalpuetz

Reputation: 5418

@nameBeginWithCapital will define metadata on a parameter and @validate will look for the parameter with such metadata and perform actual validation, am I right?

Exactly. Parameter Decorators can only be used to add metadata. The "heavy lifting" needs to be done via a method decorator, exactly as you described. A good example and an explanation can be found in the TypeScript Handbook (as you already found and which is the official source), which showcases what you are trying to achieve but with a required validation instead.

I modified the example from the handbook to suit your case and got it working on StackBlitz.

Upvotes: 1

Related Questions