如何使用TypeScript为Realm模型的属性创建索引?
解决Realm TypeScript模型索引创建报错问题
你的错误是因为同时用TypeScript类属性语法定义了模型字段,又手动声明了static schema静态属性,这在Realm的TypeScript实现里是冲突的——类模型需要用装饰器或属性注解来配置索引,不能重复定义schema。
正确写法1:使用装饰器(推荐,保留TypeScript类型检查)
- 先确保
tsconfig.json启用装饰器支持:
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true } }
- 用
@Realm.Indexed()装饰器标记需要索引的属性,无需手动写static schema:
import Realm from 'realm'; class Book extends Realm.Object<Book> { @Realm.Indexed() name!: string; price?: number; }
Realm会自动从类属性和装饰器生成对应的schema,包含索引配置。
正确写法2:单独定义schema(无类属性类型提示)
如果不想用装饰器,可以去掉类里的属性定义,只给类挂载schema:
import Realm from 'realm'; class Book extends Realm.Object<Book> {} Book.schema = { name: 'Book', properties: { name: { type: 'string', indexed: true }, price: 'int?', }, };
这种写法没有TypeScript的属性类型提示,适合不需要强类型检查的场景。
内容的提问来源于stack exchange,提问作者Mehrdad Moradi
相关产品推荐
相关产品推荐

