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
Dawson Toth
shared this idea