使用Deno API时遭遇TSC编译错误(TS2304)求解决方案
解决TypeScript跨Deno/Bun/Node编译时找不到Deno的问题
步骤1:安装环境类型依赖
先把三个环境的类型定义都装上,Node和Deno的类型需要手动安装:
# 安装Node的类型包 npm install @types/node --save-dev # 安装Deno的类型包 npm install @deno/types --save-dev
步骤2:更新tsconfig.json的类型配置
把新增的类型包加入compilerOptions.types数组,让TypeScript能识别三个环境的全局变量:
{ "compilerOptions": { "sourceMap": true, "target": "es6", "strict": true, "esModuleInterop": true, "moduleResolution": "node", "baseUrl": "./src", "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "types": ["bun-types", "@deno/types", "@types/node"] }, "include": [ "src/**/*.ts", "src/types/**/*.d.ts" ], "exclude": [ "node_modules" ] }
步骤3:添加全局类型声明(更严谨的做法)
直接引入所有类型后,TypeScript会默认认为这些全局变量在任何环境都存在,容易导致运行时出错。可以在src/types/下新建global.d.ts文件,把这些全局对象标记为可选:
declare global { var Deno: typeof import("@deno/types").Deno | undefined; var Bun: typeof import("bun-types").Bun | undefined; } export {};
这样TypeScript会提示你必须先判断变量是否存在才能访问,避免写出不安全的代码。
步骤4:代码里加环境检测逻辑
编译问题解决后,还要保证运行时在不同环境下都能正常工作,比如获取版本的逻辑可以改成这样:
const getRuntimeVersion = () => { if (typeof Deno !== 'undefined') { return Deno.version.deno; } else if (typeof Bun !== 'undefined') { return Bun.version; } else if (typeof process !== 'undefined') { return process.version; } return 'unknown'; }; // 原代码里的version字段替换成这个函数的返回值 const appInfo = { version: getRuntimeVersion() };
这样既彻底解决了编译报错,又保证了代码在三个环境下都能稳定运行,完全不用依赖// @ts-ignore这种偷懒的写法。
内容的提问来源于stack exchange,提问作者Krypton
相关产品推荐
相关产品推荐

