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

TypeScript方法装饰器无法运行,求问题排查与解决

TypeScript方法装饰器无法运行的问题解决

问题描述

我正在学习Mosh的TypeScript课程,遇到如下问题:下方代码在课程视频中运行正常,但在我的本地电脑和TypeScript Playground中均无法运行。我对装饰器相关知识不太熟悉,不清楚代码问题出在哪里,希望能得到帮助。

function Log(target: any, methodName: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value as Function;

  descriptor.value = function (...args: any) {
    console.log("before");
    original.call(this, ...args);
    console.log("after");
  };
}

class Person {
  @Log
  say(message: string) {
    console.log("Person says" + message);
  }
}

let person = new Person();
person.say("hello");

解决方案

你的代码逻辑本身没有问题,无法运行的核心原因是TypeScript装饰器目前仍属于实验性特性,必须手动开启相关配置才能启用:

1. 本地项目配置

修改项目根目录下的tsconfig.json文件,在compilerOptions中添加或调整以下选项:

{
  "compilerOptions": {
    "target": "ES5", // 目标版本至少为ES5
    "experimentalDecorators": true, // 开启实验性装饰器
    "emitDecoratorMetadata": true // 可选,若需要元数据相关功能则开启
  }
}

2. TypeScript Playground配置

点击页面右上角的「Settings」图标,进入「Compiler Options」面板,找到「Experimental Decorators」选项并勾选,保存后代码即可正常运行。

验证结果

开启配置后运行代码,控制台会输出:

before
Person sayshello
after

内容的提问来源于stack exchange,提问作者Md Sanvir Islam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:05:21