I want to create a parameter decorator that can transform the parameter value passed by the user from a string to a number:
class foo{
something(@ToNumber id: string){
console.log(id)
}
}
So I made this function (decoarator):
const ToNumber =
(target: any, propertyKey: string, parameterIndex: number) => {
const originalMethod = target[propertyKey];
target[propertyKey] = function(...args: any[]) {
args[parameterIndex] = parseInt(args[parameterIndex]);
return originalMethod.apply(this, args);
}
}
Anyway it did not work, and the output when running the something method is still a string:
const instance = new foo()
instance.something("123")
In the terminal:
[LOG]: "123" # as a string
Here is a typescript playground
I don’t know if this extra info helps, but I read something in the past about the Reflect class, but I wasn’t able to know how to integrate it into my decorator or if it’s useful in this case or not.