Allow specifying required fields on Realm.Object #5000
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What, How & Why?
The current types for
Realm.Object
(post-class based models) make it so that when you construct an object withnew MyObject(realm: Realm, objectValues: Record<string, whatever>)
, you are required to specify a value for every property of the schema inobjectValues
.In the case of schemas with default values specified, this means you would need to work around type errors if you do not want to specify an explicit value for the properties with defaults – e.g. you could specify
fieldName: undefined
which would result in the default being used, which works but is a little clumsy.This is likely to become a more common use case post-Typescript models, as we are making it very natural to specify schema defaults.
This change makes it so that all fields of the schema are optional, unless explicitly specified as part of a union type for the second type parameter:
class MyObject extends Realm.Object<MyObject, 'requiredField1' | 'requiredField2'>
– so users should specify any required fields (i.e. ones which do not have a default value) in this type parameter.If required fields are not specified in the type parameter, TypeScript will treat them as optional, which could lead to errors where required fields are not being passed in. On the other hand, this will not break existing code as we are by default relaxing the strictness of the type.
The reason behind making all fields optional by default rather than required is that core has an internal default value for all types, so this will not lead to runtime errors. It would of course be much nicer to be able to infer which fields have a default value being assigned but I don't think there's any way to express this in TypeScript.
☑️ ToDos
Compatibility
label is updated or copied from previous entryCOMPATIBILITY.md
package.json
s (if updating internal packages)Breaking
label has been applied or is not necessaryIf this PR adds or changes public API's: