Re:Why doesn't TypeScript properly type Object.keys?
by iainmerrick on Saturday June 24, 2023 @09:25AM
(#36458501)
It would be a lot nicer if it instead returned some JsonType that’s a union of all the possible JSON values. Anyone know if there’s a good reason why it doesn’t do that?
[ Parent
| on HN ]
Re:Why doesn't TypeScript properly type Object.keys?
by striking on Saturday June 24, 2023 @09:44AM
(#36458640)
You can pass an arbitrary rehydration function, which can return non-JSON-representable types
Re:Why doesn't TypeScript properly type Object.keys?
by Dylan16807 on Saturday June 24, 2023 @10:48AM
(#36459128)
It could look at the return type of your reviver function, or at least whether you passed one in.
Re:Why doesn't TypeScript properly type Object.keys?
by kristiandupont on Saturday June 24, 2023 @11:06AM
(#36459316)
There's a big discussion about this: https://github.com/microsoft/TypeScript/issues/1897. The benefit seems extremely limited to me. Valid JSON is obviously a subset of `any`, but I can't think of a situation where that particular specificity provides any value. Can you?
Re:Why doesn't TypeScript properly type Object.keys?
by iainmerrick on Saturday June 24, 2023 @08:01PM
(#36463868)
The value is when you’re parsing the JSON afterwards. It’s good to know you can match it exhaustively -- each value is either a Record<string, Json>, Json[], string, number, Boolean or null, and nothing else.
Edit to add: I think “any” is almost always a big cop-out because you couldn’t be bothered figuring out the correct type, and it often causes problems (loss of type coverage) further down the line. I admit I do use “any” in my own code when I really need to, but a library should work harder to avoid it, and the standard platform typings should work harder still.
Re:Why doesn't TypeScript properly type Object.keys?
by rcfox on Saturday June 24, 2023 @01:12PM
(#36460608)
What are the common operations you can perform on that union?
Re:Why doesn't TypeScript properly type Object.keys?
by consilient on Saturday June 24, 2023 @07:06PM
(#36463491)
You can narrow it exhaustively.
Re:Why doesn't TypeScript properly type Object.keys?
by madeofpalk on Saturday June 24, 2023 @01:36PM
(#36460830)
That's effectively what unknown would be - at least the outcome would mostly be the same. You'll end up narrowing values in just the same way.