Search code examples
typescriptreact-nativerealm

Using Typescript with Realm JS


I'm using Realm for react-native. They say if you want to use schemas on objects, you would do something like:

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

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

I want to use Typescript in my projects. The type definition for schema is ObjectClass[] where ObjectClass is defined as:

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

So, I defined my class:

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

But, the following fails:

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'.


Solution

  • The schema property on MyApp should be static (and this means you won't be able to implement the interface ObjectClass):

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