1

I am able to get a method's parameter types easily with ReflectAPI:

Reflect.getMetadata('design:paramtypes', target, propertyKey);

but, when I try to get a function's parameter types it is always returning undefined. I have tried to do with these example functions:

const foo = (bar: Bar) => void 0;

function foo(bar: Bar) {}
export function foo(bar: Bar) {}

And also I read that TypeScript only emits metadata when you decorate a class and method. So, how can I get a function's metadata?

1 Answers1

-1

If you're talking about getting function parameter type at run-time, it's impossible at the time of writing since TypeScript do not support this due to type erasure during transpilation. In other words, type information are thrown away once TypeScript is compiled into JavaScript.

However, if you're talking about getting function parameter's type compile-time, then it's possible with Conditional Type. The answer can be found at https://stackoverflow.com/a/51851844/6587634

Wong Jia Hau
  • 1,887
  • 12
  • 19
  • This is incorrect. It's possible to get some types at run-time with decorators, Reflection API and enabling certain flags in the tsconfig. A popular framework which uses this all the time is Angular. – Lazar Ljubenović Jan 01 '21 at 23:12
  • @LazarLjubenović do you mind providing an example? – Wong Jia Hau Jan 02 '21 at 02:36
  • The OP's post has a code snippet for `design:paramtypes`. Search for “reflect-metadata” on this page: https://www.typescriptlang.org/docs/handbook/decorators.html – Lazar Ljubenović Jan 02 '21 at 08:39
  • If that is correct, I think you should be able to provide a working example for the OP? – Wong Jia Hau Jan 02 '21 at 08:46