How can you access the value of a method parameter in a decorator ?
export const NullParameterCheck = (target: Object, key: string, index: number) => {
// how to get the value of the marked parameter in this case 'model'
// ... do something with that value here.
}
this is how i use it
public SetToolbar(@NullParameterCheck model: ToolbarModel): void {
}
All that i could found is how to declare a parameter decorator and log each of its parameters
Thanks.
The decorator is invoked when the class is declared, not when the method is invoked. You can replace the original method to intercept and change the original parameter, however you can't replace the method from a parameter decorator, you can only do so from a method decorator, so you would need to add the decorator to the function:
const NullParameterCheck = (index: number) => (target: any, key: string, propDesc: PropertyDescriptor) => {
let originalFunction: Function = propDesc.value;
propDesc.value = function () {
let argValue = arguments[index];
let newArgs = [];
for (let i = 0; i < arguments.length; i++)newArgs.push(arguments[i]);
newArgs[index] = argValue || {};
return originalFunction.apply(this, newArgs);
};
return propDesc;
}
class ToolbarModel { }
class x {
@NullParameterCheck(0)
public SetToolbar( model: ToolbarModel): void {
console.log(model);
}
}
new x().SetToolbar(null);