Skip to content

Conversation

@msanchezdev
Copy link

@msanchezdev msanchezdev commented Dec 11, 2025

Because keys are always strings in Javascript, a record will never parse when the schema specifies it should be a number.

const schema = z.record(z.number(), z.number());
schema.parse({ 1: 100, 2: 88, 3: 99, 4: 60 })

A workaround or the right way would be to coerce the number instead:

const schema = z.record(z.coerce.number(), z.number());
schema.parse({ 1: 100, 2: 88, 3: 99, 4: 60 })

Only problem being the record throwing type error as the coerced number doesnt have a number input.

This seems to be okay as the number type doesnt leek anywhere it should not:

z.record(z.coerce.number(), z.number()) // Record<number, number>
Object.keys(result); // string[]
Object.entries(result); // [string, number][]
for (const key /*: string */ in result) {

}

I am aware of the docs mentioning using string for record keys (image below) but I think we can embrace using coerced number without problem (or any other schema that outputs a valid key).
image

Asserts:

@vercel
Copy link
Contributor

vercel bot commented Dec 11, 2025

@msanchezdev is attempting to deploy a commit to the colinhacks Team on Vercel.

A member of the Team first needs to authorize it.

@msanchezdev
Copy link
Author

@colinhacks I'm interested in this comment of yours in #4665 (comment), and would like to know if there is something I'm missing that would make this change not viable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant