本文介绍了Typescript使用装饰器获取参数的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在装饰器中访问方法参数的值?

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. 
}

这就是我的使用方式

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); 

这篇关于Typescript使用装饰器获取参数的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 14:29