reflect-metadata icon indicating copy to clipboard operation
reflect-metadata copied to clipboard

How to get parameter types from function?

Open yantrab opened this issue 6 years ago • 2 comments

Hi, can you help me with how to get parameters types from function? I can get constructor parameter type by Reflect.getMetadata('design:paramtypes', target) but get nothing for Reflect.getMetadata('design:paramtypes', target.prototype.somemethod)

yantrab avatar Dec 19 '19 07:12 yantrab

To get the parameter type from a method we can invoke Reflect.getMetadata('design:paramtypes', target, propertyName') from inside a decorator function.

For example:

import 'reflect-metadata';

class MathClass {
  @LogParamTypes()
  multiply(numA: number, numB: number ): number {
    return numA * numB
  }
}

function LogParamTypes() {
  return LogParamTypesFactory
}

function LogParamTypesFactory(target, propertyName, descriptor) {
  const paramTypes = Reflect.getMetadata('design:paramtypes', target, propertyName)
  console.log("paramTypes:", paramTypes)

  console.log(paramTypes[0].name)
  console.log(paramTypes[1].name)
}

absorpheus avatar Mar 15 '20 22:03 absorpheus

To achieve it,by using Reflect.getMetadata('design:paramtypes', target.prototype, methodName)

gylove1994 avatar Aug 22 '22 09:08 gylove1994

@abdullahchaudhry Why I get paramTypes: undefined if use such decorator in Nuxt 3? It's because of vite/esbuild?

imcm7 avatar Oct 11 '23 13:10 imcm7

You would need to check the generated output to see if a __metadata() call is issued for the multiply method. Unfortunately, I cannot speak to what level of support vite, esbuild, or nuxt provides for the --emitDecoratorMetadata flag.

rbuckton avatar Oct 11 '23 17:10 rbuckton

@rbuckton import rollupPluginTs from '@rollup/plugin-typescript'; and add it to nuxt.config nitro.esbuild.rollupConfig.plugins work

rollupPluginTs({
  include: ['server/controllers/*.ts'],
  tsconfig: 'tsconfig.decorators.json',
}),

imcm7 avatar Oct 12 '23 18:10 imcm7

@rbuckton now I have

paramTypes [ [Function: Object], [Function: Object] ] designType [Function: Function] returnTypes [Function: Promise]

but expect something like User, String, Number

imcm7 avatar Oct 13 '23 06:10 imcm7

It's because type is Partial<User>, with User type all is ok.

imcm7 avatar Oct 13 '23 06:10 imcm7

Closing as it seems the original question has been answered. As far as the value of design:paramtypes, the behavior of TypeScript's --emitDecoratorMetadata behavior is better discussed on the TypeScript repository.

rbuckton avatar Dec 14 '23 20:12 rbuckton