在领域JS中使用Typescript
我正在使用Realm作为react native。他们说,如果要在对象上使用模式,可以执行以下操作:在领域JS中使用Typescript,typescript,react-native,realm,Typescript,React Native,Realm,我正在使用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的类型定义
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]})
类型为“typeof MyApp”的参数不能分配给类型为“ObjectClass”的参数。类型“typeof MyApp”中缺少属性“schema”。
MyApp
上的schema
属性应该是静态的(这意味着您将无法实现接口ObjectClass
):
我认为这意味着,除非我弄错了,否则我不会真正将typedefs用于realm。您不应该在类上显式实现
ObjectClass
接口,当您在类上定义静态schema
属性时,就会推断出它。如果这看起来不直观,我很抱歉,但是TypeScript不允许我们在接口上定义静态成员。这实际上不是正确的方法,因为现在,来自领域的任何对象查询都将有一个对象
原型,而不是领域.Object
。这意味着像.entries()
、.keys()
和.toJSON()
这样的属性将不存在,这让我很长一段时间都很头疼。
class MyApp {
static schema = { name: 'int', properties: { version: 'int' } };
}