使用lowdb时TypeScript报“属性不存在”错误的解决方法
解决Lowdb在TypeScript中提示“Property 'entries' does not exist”的警告
问题描述
在Svelte 4环境的src/lib/mylib.ts文件中,使用Lowdb读取JSON文件的代码可正常运行,但TypeScript持续抛出以下警告:
Property 'entries' does not exist on type '{}'.ts(2339)Property 'entries' does not exist on type 'unknown'.ts(2339)
示例代码:
import { Low } from 'lowdb' import { JSONFile } from 'lowdb/node' const adapter = new JSONFile('db.json') const db = new Low(adapter, { entries: [] }) await db.read() const { entries } = db.data // destructure entries.push({ id: 1, name: 'Entry' }) console.log('entries:', entries[0])
问题原因
这不是VSCode Linter的问题,本质是TypeScript无法自动推断db.data的具体类型。Lowdb通过泛型实现类型支持,若不显式指定数据结构,TypeScript会将db.data推断为unknown或{},自然无法识别entries属性。
解决方法
方法1:显式定义数据库类型接口(推荐)
通过TypeScript接口明确数据库的数据结构,同时给JSONFile和Low实例指定泛型参数,让TypeScript获得完整的类型信息:
import { Low } from 'lowdb' import { JSONFile } from 'lowdb/node' // 定义数据库数据结构的接口 interface Database { entries: { id: number; name: string }[] } // 创建适配器时指定泛型 const adapter = new JSONFile<Database>('db.json') // 初始化Low实例时绑定类型,同时传入默认值 const db = new Low<Database>(adapter, { entries: [] }) await db.read() // 用!断言data不为undefined(初始化有默认值,read后必然存在) const { entries } = db.data! entries.push({ id: 1, name: 'Entry' }) console.log('entries:', entries[0])
方法2:临时类型断言(快速临时解决)
如果不想定义接口,可直接对db.data做类型断言,快速消除警告(但缺乏长期类型约束,不推荐用于正式代码):
import { Low } from 'lowdb' import { JSONFile } from 'lowdb/node' const adapter = new JSONFile('db.json') const db = new Low(adapter, { entries: [] }) await db.read() // 直接断言db.data的类型 const { entries } = db.data as { entries: { id: number; name: string }[] } entries.push({ id: 1, name: 'Entry' }) console.log('entries:', entries[0])
注意事项
- 不要忽略这个警告:虽然代码能运行,但类型缺失会导致后续开发中无法获得TypeScript的类型校验和智能提示,增加潜在bug风险。
- 若
db.json文件不存在,Lowdb会自动使用初始化时传入的{ entries: [] }作为默认值,因此用!断言db.data不为undefined是安全的。
内容的提问来源于stack exchange,提问作者poinck
相关产品推荐
相关产品推荐

