如何检测TypeScript装饰器中的方法是否为async函数?
在TypeScript装饰器中检测异步函数的方法
可行检测方法
通过构造函数名称判断
异步函数的constructor.name固定为AsyncFunction,可以直接做运行时判断:function catchError(target: any, propertyName: string, descriptor: PropertyDescriptor) { const method = descriptor.value; if (method.constructor.name === 'AsyncFunction') { // 异步函数的处理逻辑 console.log(`${propertyName} 是异步函数`); } }注意:代码被压缩混淆时,构造函数名称可能被篡改,导致判断失效。
通过函数字符串特征判断
异步函数的toString()结果会包含async关键字,用正则匹配更稳定:function catchError(target: any, propertyName: string, descriptor: PropertyDescriptor) { const method = descriptor.value; if (/^async function/.test(method.toString())) { // 异步函数的处理逻辑 } }多数压缩工具不会移除
async关键字,所以这种方式兼容性更强。结合类型守卫做编译时辅助
虽然运行时无法直接获取TypeScript类型,但可以用类型守卫让TS自动推断类型:type AsyncFunction = (...args: any[]) => Promise<any>; function isAsyncFunction(fn: any): fn is AsyncFunction { return fn.constructor.name === 'AsyncFunction' || /^async function/.test(fn.toString()); } function catchError(target: any, propertyName: string, descriptor: PropertyDescriptor) { const method = descriptor.value; if (isAsyncFunction(method)) { // TS会自动推断method为AsyncFunction类型 } }
为什么容易找不到解决方案
TypeScript编译后会把async函数转换为基于Promise的普通函数,编译时的类型信息不会保留到运行时。这类检测依赖函数的运行时特征,不属于TS核心语法知识点,相关细节较少被系统性整理,所以容易找不到直接答案。
内容的提问来源于stack exchange,提问作者elija
相关产品推荐
相关产品推荐

