You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TypeScript为Realm模型的属性创建索引?

解决Realm TypeScript模型索引创建报错问题

你的错误是因为同时用TypeScript类属性语法定义了模型字段,又手动声明了static schema静态属性,这在Realm的TypeScript实现里是冲突的——类模型需要用装饰器或属性注解来配置索引,不能重复定义schema。

正确写法1:使用装饰器(推荐,保留TypeScript类型检查)

  1. 先确保tsconfig.json启用装饰器支持:
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
  1. 用@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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 09:42:10