TypeScript调用stopword.removeStopwords报undefined属性读取错误
TypeScript 项目调用 stopword 抛出
Cannot read property 'removeStopwords' of undefined 修复方案 问题复现
开发停用词处理功能时运行代码触发如下报错:
TypeError: Cannot read property 'removeStopwords' of undefined at getSentiment (/home/karlito/projects/twitter/src/app.ts:23:39) at Object.<anonymous> (/home/karlito/projects/twitter/src/app.ts:31:13) at Module._compile (node:internal/modules/cjs/loader:1109:14) at Module._compile (/home/karlito/projects/twitter/node_modules/source-map-support/source-map-support.js:568:25) at Module.m._compile (/tmp/ts-node-dev-hook-30469514417241084.js:69:33) at Module._extensions..js (node:internal/modules/cjs/loader:1138:10) at require.extensions..jsx.require.extensions..js (/tmp/ts-node-dev-hook-30469514417241084.js:114:20) at require.extensions.<computed> (/tmp/ts-node-dev-hook-30469514417241084.js:71:20) at Object.nodeDevHook [as .ts] (/home/karlito/projects/twitter/node_modules/ts-node-dev/lib/hook.js:63:13) at Module.load (node:internal/modules/cjs/loader:989:32) [ERROR] 18:44:36 TypeError: Cannot read property 'removeStopwords' of undefined
此前尝试的调试操作均未生效:
- 将空值判断逻辑中的
!str.trim()替换为str.trim(),运行后控制台仅输出两次0 - 将
fixedSpelling的类型标注为any,同时将getSentiment方法的参数类型修改为str: string | undefined
对应业务代码:
// @ts-ignore import aposToLexForm from "apos-to-lex-form"; import { WordTokenizer } from "natural"; // @ts-ignore import SpellCorrector from 'spelling-corrector'; import stopword from "stopword"; const tokenizer = new WordTokenizer(); const spellCorrector = new SpellCorrector(); spellCorrector.loadDictionary(); function getSentiment(str: string): -1 | 0 | 1 { if (!str.trim()) { return 0; } const lexed = aposToLexForm(str).toLowerCase().replace(/[^a-zA-Z\s]+/g, ""); const tokenized = tokenizer.tokenize(lexed); const fixedSpelling = tokenized.map((word) => spellCorrector.correct(word)); const stopWordsRemoved = stopword.removeStopwords(fixedSpelling); console.log(stopWordsRemoved); return 0; } console.log(getSentiment('This is awesome!')) console.log(getSentiment('Logging is super duper cool!'))
根因分析
报错核心是stopword的导入写法错误:stopword是标准CommonJS模块,没有提供ES Module默认导出,使用import stopword from "stopword"写法导入时,运行时拿到的stopword变量实际值为undefined,后续调用removeStopwords方法时自然会抛出读取undefined属性的错误。
之前的调试操作完全没有触及导入逻辑这个根因,所以无法解决问题:
- 修改
!str.trim()判断逻辑只会反转空字符串的分支走向,和stopword的调用逻辑无关 - 修改类型标注仅能跳过TypeScript的静态类型检查,无法修复运行时导入值为undefined的实际问题
修复方案
将stopword的导入语句替换为以下任意一种写法即可:
- ES Module 命名空间导入(无需额外修改tsconfig,兼容性最好)
import * as stopword from "stopword";
- CommonJS 导入(适配Node.js原生模块规范)
const stopword = require("stopword");
如果不想修改导入语句,也可以在项目的tsconfig.json中开启esModuleInterop: true配置,让TypeScript自动处理CommonJS模块的默认导入兼容,但这种方式依赖编译配置,不如直接修改导入语句稳妥。
修改后重新运行代码,即可正常执行停用词移除逻辑,不会再抛出该类型错误。
内容的提问来源于stack exchange,提问作者Kakarot12
相关产品推荐
相关产品推荐

