Use Enums in Generated Realm Object Models
When the JSON Schema for a collection contains a string enumeration, like the following:
{
"properties": {
"_id": {
"bsonType": "objectId"
},
"enumExample": {
"bsonType": "string",
"enum": [
"Foo",
"Bar",
"Baz"
],
"title": "The type of entity that was favorited, such as a Workout."
}
},
"required": [
"_id",
"enumExample"
],
"title": "EnumExample"
}
... the generated Realm Object Models don't take advantage of the limited possible values. I've generated all of the available languages, and they all generate variations of a simple string
.
Here's TypeScript as an example:
import Realm from "realm";
export type EnumExample = {
_id: Realm.BSON.ObjectId;
enumExample: string;
};
export const EnumExampleSchema = {
name: 'EnumExample',
properties: {
_id: 'objectId',
enumExample: 'string'
},
primaryKey: '_id',
};
Ideally, the generated type would be narrowed. Even more ideal would be enforcement of that at runtime, but I'm less knowledgeable about how that could work!
import Realm from "realm";
export type EnumExample = {
_id: Realm.BSON.ObjectId;
enumExample: "Foo" | "Bar" | "Baz"; // <--- this is the only line that changed
};
export const EnumExampleSchema = {
name: 'EnumExample',
properties: {
_id: 'objectId',
enumExample: 'string'
},
primaryKey: '_id',
};
1
vote
![](https://secure.gravatar.com/avatar/ae9f5d229f6d05bdb15f26ede04e3806?size=40&default=https%3A%2F%2Fassets.uvcdn.com%2Fpkg%2Fadmin%2Ficons%2Fuser_70-6bcf9e08938533adb9bac95c3e487cb2a6d4a32f890ca6fdc82e3072e0ea0368.png)