简体   繁体   中英

How to get a function parameter types

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM