解决 TypeScript 报错 TS2339: Property does not exist on type 类型扩展修复
排查 TypeScript 访问对象属性提示 TS2339: Property '...' does not exist on type '...' 错误,使用模块补充、类型扩展与索引签名安全解决。
问题现象
在访问全局对象(如 window)、Express 的 req.user、或访问动态解析的对象键时,TypeScript 编译器报错:
src/routes/auth.ts:15:20 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
15 const userId = req.user.id;
~~~~
或者在访问浏览器全局变量时:
error TS2339: Property 'myCustomLib' does not exist on type 'Window & typeof globalThis'.
触发根因
TypeScript 严格根据类型声明(Declaration Files, .d.ts)来判定一个对象拥有的合法属性集合:
- 框架原生类型定义中不包含自定义挂载属性:Express 的原生
Request接口默认只有headers、body等属性,业务认证中间件动态挂载的user并没有在官方@types/express中声明; - 全局作用域未补齐:第三方 SDK(如 Google Maps、微信 JS-SDK)通过
<script>注入了window.mySdk,但当前项目 TS 编译器对此一无所知; - 联合类型只允许访问交集属性:类型为
Cat | Dog时,若尝试直接访问仅在 Dog 上存在的bark属性,TS 会拦截。
解决步骤
1. 使用声明合并(Declaration Merging)扩展第三方库接口
在项目中创建类型声明文件(如 src/types/express.d.ts),扩展 Express 的 Request 接口:
import { UserPayload } from '../models/user';
declare global {
namespace Express {
interface Request {
user?: UserPayload; // 声明自定义的 user 字段
}
}
}
export {}; // 确保作为模块被加载
并在 tsconfig.json 的 include 列表中包含该目录:"include": ["src/**/*"]。
2. 扩展全局 Window 接口
在 src/types/global.d.ts 中声明全局浏览器变量:
declare global {
interface Window {
myCustomLib: {
init: () => void;
version: string;
};
}
}
export {};
3. 针对动态字典对象添加索引签名(Index Signature)
如果对象属于键名不固定的通用配置字典:
interface DynamicConfig {
baseUrl: string;
[key: string]: any; // 允许任意其他自定义键访问
}
验证确认
再次运行代码静态检查:
npx tsc --noEmit
TypeScript 完美识别 req.user 与 window.myCustomLib 的类型定义,并在 IDE 中支持自动补全,TS2339 错误彻底修复。


