You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:10:35