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

Generic type for toJSON #5165

Open thaynarbo opened 1 year ago

thaynarbo commented 1 year ago

Problem

In our application, we're using .toJSON a lot because we work with immutability and so we copy the data by using js spreading operation and when the spreading takes place the data is not available anymore, toJSON solves that problem. I wasn't seeing any problem with using toJSON for that matter, but after upgrading Realm to a newer version, I noticed that the type is returning something different Record<string, unknown>. Is there a way I could type it without having to force the type? The cast doesn't work here because they are a lot different.

image

from Realm types folder image

current realm version: 11.0.0 current react native version: 0.70.4 current typescript version: 4.8.3

Solution

It would be better if the type was generic instead of Record<string,unknown>

How important is this improvement for you?

Would be a major improvement

kraenhansen commented 1 year ago

Sorry for the long wait here. It seems like a valuable enhancement to me. Would it work if toJSON took a generic which defaulted to Record<string, unknown>, like this?

toJSON<T = Record<string, unknown>>(): T;

That way, calling code could pass their known good type:

const json = obj.toJSON<IProfissao>();
thaynarbo commented 1 year ago

That looks really great! It would totally help increase the typing for us

kraenhansen commented 1 year ago

I've moved this to the backlog and tagged it as "quick win" 🤞

doelgonzo commented 1 year ago

Just bumping this, is this still in plan? Saw 12.0.0 was release but this was not part of it. I would happily write up a PR if it would help

mwimbledon commented 5 months ago

Any update on this?

mayckondf commented 2 months ago

up ⬆️