logoalt Hacker News

VanCodingyesterday at 5:04 PM5 repliesview on HN

That's not what I mean. Even though it is serializable, it's still not the same when you serialize/deserialize it.

For example `JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))).subtract({ years: 1})` won't work, because it misses the prototype and is no longer an instance of Temporal.PlainYearMonth.

This is problematic if you use tRPC for example.


Replies

flyingmeteoryesterday at 5:21 PM

You would need to use the `reviver` parameter of `JSON.parse()` to revive your date strings to Temporal objects. As others have said, it's a simple `Temporal.from()`

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

show 2 replies
rimunroeyesterday at 6:14 PM

> For example `JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))).subtract({ years: 1})` won't work, because it misses the prototype and is no longer an instance of Temporal.PlainYearMonth.

I don't know if I'm missing something, but that's exactly how I'd expect it to compose. Does the following do what you wanted your snippet to do?

  Temporal.PlainYearMonth.from(JSON.parse(JSON.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))))
JSON.stringify and JSON.parse should not be viewed as strict inverses of each other. `JSON.parse(JSON.stringify(x)) = x` is only true for a for a small category of values. That category is even smaller if parsing is happening in a different place than stringification because JSON doesn't specify runtime characteristics. This can lead to things like JSON parsing incorrect in JS because they're too large for JS to represent as a number.
aubergeneyesterday at 11:27 PM

This seems more to do with how JSON works than Temporal. There are libraries such as Devalue which will handle this for you

`devalue.parse(devalue.stringify(Temporal.PlainYearMonth.from({year:2026,month:1}))).subtract({ years: 1})`

https://www.npmjs.com/package/devalue

tshaddoxyesterday at 10:42 PM

This is also true of JavaScript Date instances, so I’m curious what solution you had that did work with raw JSON stringify and parse.

gowldyesterday at 5:20 PM

Would a plain data object be an instance of PlainYearMonth?

If not, that regardless of being plain data or a serialized object with functions, you'd still need to convert it to the type you want.