realm / realm-js

Realm is a mobile database: an alternative to SQLite & key-value stores
https://realm.io
Apache License 2.0
5.72k stars 564 forks source link

Inaccurate Return Type for `toJSON` Method in `RealmObject` #6728

Open CacaoRick opened 2 months ago

CacaoRick commented 2 months ago

I've noticed a potential issue with the toJSON method's return type in the RealmObject class. According to the current TypeScript definition, the toJSON method is expected to return a DefaultObject. However, considering the generic type T used throughout the RealmObject<T> class, it seems more appropriate for toJSON to return a type T instead, especially since the method processes and returns a plain object representation of the instance.

Current Implementation:

export class RealmObject<T = DefaultObject, RequiredProperties extends keyof OmittedRealmTypes<T> = never> {

  // ...

  toJSON(_?: string, cache?: unknown): DefaultObject;
  toJSON(_?: string, cache = new JSONCacheMap()): DefaultObject {
    // ...
    const result: DefaultObject = {};
    // Implementation details...
    return result;
  }

  // ...
}

Source:

Object.ts#L383-L410

Documentation Reference:

RealmObject.toJSON

Suggested Change:

It might be more accurate for the toJSON method to return a type T to reflect the actual data structure of the RealmObject instance. This change would align the method's return type with the generic type used in the class definition.

Could you please review this and consider updating the TypeScript definition if appropriate? Thank you for looking into this matter.

sync-by-unito[bot] commented 2 months ago

➤ PM Bot commented:

Jira ticket: RJS-2838

CacaoRick commented 2 months ago

If OmittedRealmTypes can remove model properties from a Realm Object, perhaps it should return OmittedRealmTypes<T>?