Realm Schema中completedSampleTreesCount属性定义报错求助
问题描述
错误信息:
属性'completedSampleTreesCount'在'Inventory'上的类型声明无效:定义属性对象时,不能在'type'中使用简写'?'。
我的Inventory对象代码如下:
const Inventory = { name: 'Inventory', primaryKey: 'inventory_id', properties: { // other properties... completedSampleTreesCount: { type: 'int?', default: 0, }, // other properties... }, };
我在React Native v0.72.3应用中使用Realm v12.0.0-rc.1作为数据库,已按照Realm文档定义Schema,但仍出现上述错误。现求助:
- 该错误产生的原因是什么?
- 我的Schema定义是否有误?
- Realm中声明可选属性的正确方式是什么?
问题解答
错误原因
Realm的属性定义语法有明确区分:当直接用字符串声明属性类型时,可以用?简写标记可选;但当你用对象形式定义属性(包含type、default等额外配置项)时,不允许在type字段里加?,必须通过专门的配置字段声明可选性。
Schema定义问题
你的Schema确实存在错误:在对象形式的属性配置中,你使用了type: 'int?',这不符合Realm的语法规则,直接触发了报错。
正确声明可选属性的方式
当用对象形式定义属性时,需要添加optional: true字段来标记属性为可选,type字段仅保留基础类型即可:
const Inventory = { name: 'Inventory', primaryKey: 'inventory_id', properties: { // other properties... completedSampleTreesCount: { type: 'int', optional: true, default: 0, }, // other properties... }, };
另外补充两种常见的可选属性声明场景:
- 若不需要设置默认值等额外配置,可直接用简写形式:
completedSampleTreesCount: 'int?' - 如果你使用TypeScript开发,还可以结合类型注解与
optional: true配置来定义,但当前JS写法用上述方案即可。
内容的提问来源于stack exchange,提问作者Mayank kumawat
相关产品推荐
相关产品推荐

