能否在React中使用TypeScript 5.0装饰器?
启用TypeScript 5.0新版装饰器的方法
当然可行,你需要在TypeScript配置中做以下修改:
- 在
tsconfig.json里,将compilerOptions下的experimentalDecorators设为false(旧版装饰器依赖该选项,新版无需启用) - 开启
decoratorsBeforeExport选项(控制装饰器语法位置,新版推荐将装饰器放在export语句之前) - 确保你的TypeScript版本为5.0及以上,低于该版本不支持新版装饰器
配置示例:
{ "compilerOptions": { "target": "ES2022", "module": "ESNext", "strict": true, "experimentalDecorators": false, "decoratorsBeforeExport": true } }
新版装饰器的调用逻辑和旧版不同,以类装饰器为例,它会直接接收类作为唯一参数:
function ClassDecorator<T extends new (...args: any[]) => {}>(target: T) { return class extends target { newProperty = "new property"; hello = "override"; }; } @ClassDecorator class Greeter { property = "property"; hello: string; constructor(m: string) { this.hello = m; } }
完成配置后,装饰器就会按照TypeScript 5.0的规范执行,不再使用旧版的参数逻辑。
内容的提问来源于stack exchange,提问作者Ahsoka
相关产品推荐
相关产品推荐

