TypeScript使用Object.entries遇TS2550错误,tsconfig配置正常求排查
解决TypeScript中Object.entries()报错TS2550的问题
问题重现
业务代码
const getEntries = <T, K extends keyof T>(data: T) => Object.entries(data) as [keyof T, T[K]][];
tsconfig.json配置
{ "compilerOptions": { "target": "es2019", "module": "CommonJS", "outDir": "out", "sourceMap": true, "lib": [ "dom", "es2019" ] } }
错误提示
error TS2550: Property 'entries' does not exist on type 'ObjectConstructor'.
问题原因及解决方法
1. TypeScript版本过低
Object.entries()是ES2017引入的API,低于3.0版本的TypeScript没有为该方法提供类型声明。直接升级TypeScript到3.0及以上版本(推荐4.x或最新稳定版)即可解决。
2. 补充lib配置项
尽管target已设为es2019,但部分场景下需要显式添加es2017.object库,确保对象新增方法的类型定义被正确加载。修改tsconfig.json的lib数组:
{ "compilerOptions": { "target": "es2019", "module": "CommonJS", "outDir": "out", "sourceMap": true, "lib": [ "dom", "es2019", "es2017.object" ] } }
3. 排查自定义类型冲突
检查项目中的.d.ts声明文件,确认是否存在覆盖全局Object类型的代码——这类自定义声明可能会丢失entries方法的类型定义,删除或修改冲突代码即可。
代码优化建议
原代码中的泛型K属于冗余定义,可简化为:
const getEntries = <T>(data: T) => Object.entries(data) as [keyof T, T[keyof T]][];
内容的提问来源于stack exchange,提问作者Odai
相关产品推荐
相关产品推荐

