Specify valid keys in Record
See original GitHub issueIn TS, I can define an object like so:
type Flags = Record<"flag1"|"flag2", boolean>
or:
type Flags = {[k in "flag1"|"flag2"]: boolean}
It doesn’t seem there’s any way to accomplish this now in zod? I have lots of TS types using this pattern with large unions that I really don’t want to duplicate everywhere as z.object
keys, so this would be handy to get full parity with TS.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:10 (2 by maintainers)
Top Results From Across the Web
Specify valid keys in Record · Issue #55 · colinhacks/zod
I often use record types with unions that define required keys, for objects in which the value types are the same throughout. It's...
Read more >Define a list of optional keys for Typescript Record
I want to type an object which can only have keys 'a', 'b' or 'c' ...
Read more >Valid Keys for a Record or File - IBM
The key for a file is determined by the valid keys for the record types in that file. The file's key is determined...
Read more >TypeScript | Record Utility Type - [2022 Guide] - Daily Dev Tips
By doing this, we ensure that only valid keys can be passed. Let's say we have a type of admin user (a weird...
Read more >TypeScript's Record Type Explained | by Sunny Sun
At face value, it says the Record type creates an object type that has properties of type Keys with corresponding values of type...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Found a seemingly workable solution to this:
Can be used like so:
Perhaps worth adding to the core?
I was surprised to see that records with literals and zod enums work perfectly fine, as tests in this general area show https://github.com/colinhacks/zod/blob/cc8ad1981ba580d1250520fde8878073d4b7d40a/src/__tests__/record.test.ts#L10-L17 so perhaps the bug directly above my comment is solved?
There’s a couple of interesting things though. Records in ts enforce that all of their keys are present. e.g.:
Note that the number fields are required and not
{ f1?: number; f2?: number }
. So the approach described again in @akomm’s comment is not equivalent even in terms of the actual record parsing. Sofails to throw. That goes against my expectation at least. Same could be said of @danenania’s solution, where the fields are explicitly and intentionally made optional.
In that line, I like this as a util:
and some tests to prove that RecordOf functions very similarly to ts’s Record:
as the last test says, could always
SolarSystemZ.optional()
to get the alternative behavior