React组件中初始化TurndownService报错TS2351的问题求助
问题原因与解决方法
错误原因
报错TS2351: This expression is not constructable. Type 'String' has no construct signatures.的核心原因是:你导入的TurndownService并非可实例化的构造函数,而是被解析成了字符串类型。这通常是由于模块导入方式与turndown的实际导出结构不匹配,或是TypeScript类型定义缺失导致的。
正确解决步骤
1. 修正导入方式
turndown的ES模块采用命名导出,而非默认导出,因此需要调整导入语句为命名导入:
import { TurndownService } from 'turndown';
2. 安装TypeScript类型定义(TypeScript项目必做)
如果你的项目使用TypeScript,必须安装对应的类型声明包,否则TypeScript无法识别turndown的类型结构:
npm install @types/turndown --save-dev # 或使用yarn yarn add @types/turndown --dev
3. 验证初始化代码
修正导入后,初始化逻辑即可正常运行:
const handlePostButtonClick = () => { // Convert html to markdown const turndownService = new TurndownService(); const convertedMarkdown = turndownService.turndown(html); // 后续业务逻辑 }
额外排查方案
- 若使用turndown旧版本(v6及以下),可能存在导出结构差异,建议升级到最新版本:
npm install turndown@latest - 检查
tsconfig.json中的moduleResolution配置,确保设置为node16或bundler,以正确解析ES模块的导出规则。
内容的提问来源于stack exchange,提问作者ekinkoseoglu
相关产品推荐
相关产品推荐

