【问题标题】:Using Typescript with Realm JS将 Typescript 与 Realm JS 一起使用
【发布时间】:2017-11-12 05:06:28
【问题描述】:

我将 Realm 用于 react-native。他们说如果你想在对象上使用模式,你会这样做:

class Person {
  [...]
}
Person.schema = PersonSchema;

// Note here we are passing in the `Person` constructor
let realm = new Realm({schema: [CarSchema, Person]});

我想在我的项目中使用 Typescript。 schema 的类型定义为 ObjectClass[],其中 ObjectClass 定义为:

interface ObjectClass {
    schema: ObjectSchema;
}
interface ObjectSchema {
    name: string;
    primaryKey?: string;
    properties: PropertiesTypes;
}
[ omitted the rest b/c that's not where the type fails ]

所以,我定义了我的班级:

class MyApp implements ObjectClass{
    schema: { name: 'int', properties: { version: 'int' } }
}

但是,以下失败:

let realm = new Realm({schema: [MyApp]})

Argument of type 'typeof MyApp' is not assignable to parameter of type 'ObjectClass'. Property 'schema' is missing in type 'typeof MyApp'.

【问题讨论】:

    标签: typescript react-native realm


    【解决方案1】:

    MyApp 上的 schema 属性应该是静态的(这意味着您将无法实现接口 ObjectClass):

    class MyApp {
        static schema = { name: 'int', properties: { version: 'int' } };
    }
    

    【讨论】:

    • 我认为这意味着我将无法真正将 typedef 用于领域,除非我弄错了。
    • 你不应该在你的类上显式地实现ObjectClass 接口,当你在你的类上定义静态schema 属性时会推断它。如果这看起来不直观,我很抱歉,但是 TypeScript 不允许我们在接口上定义静态成员。
    • 这实际上不是正确的方法,因为就目前而言,任何来自 Realm 的对象查询都将具有 Object 原型,而不是 Realm.Object。这意味着.entries().keys().toJSON() 之类的属性将不存在,这让我很头疼了好一阵子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2018-04-16
    • 2016-09-24
    • 2017-02-19
    • 2019-06-06
    • 2015-03-09
    • 2012-12-14
    相关资源
    最近更新 更多