How to get function parameter names/values dynamically?

前端 未结 30 2595
说谎
说谎 2020-11-22 00:13

Is there a way to get the function parameter names of a function dynamically?

Let’s say my function looks like this:

function doSomething(param1, par         


        
30条回答
  •  执念已碎
    2020-11-22 00:30

    As this has not yet been mentioned, if you are using Typescript you can emit meta-data when using Decorators which will allow you to get the parameter names and types.

    Metadata will only be emitted if the class/function/prop has a decorator on it.
    It doesn't matter which decorator.

    This feature can be enabled by setting emitDecoratorMetadata to true inside tsconfig.json

    {
      "compilerOptions": {
        "emitDecoratorMetadata": true
      }
    }
    

    As the metadata is still an early proposal the reflect-metadata package must be installed or Reflect.getMetadata will not be defined.

    npm install reflect-metadata
    

    You can use it as follows:

    const AnyDecorator = () : MethodDecorator => {
        return target => { }
    }
    
    class Person{
        @AnyDecorator()
        sayHello(other: Person){}
    }
    const instance = new Person();
    const funcType = Reflect.getMetadata('design:type', instance.sayHello);
    const funcParams = Reflect.getMetadata('design:paramtypes', instance.sayHello);
    

    In newer versions of Angular for instance this is used to determine what to inject -> https://stackoverflow.com/a/53041387/1087372

提交回复
热议问题