How to get parameter types from function?
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)
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)
}
To achieve it,by using
Reflect.getMetadata('design:paramtypes', target.prototype, methodName)
@abdullahchaudhry Why I get paramTypes: undefined if use such decorator in Nuxt 3?
It's because of vite/esbuild?
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 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',
}),
@rbuckton now I have
paramTypes [ [Function: Object], [Function: Object] ] designType [Function: Function] returnTypes [Function: Promise]
but expect something like User, String, Number
It's because type is Partial<User>, with User type all is ok.
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.