Tim Marcus Moore - I found that z.record evalua...

I found that z.record evaluates non-enumerable property keys. I'm not sure whether this is a bug or expected behaviour. It was unexpected to me. I ran into this validating a MobX observable object using a z.record with z.string() keys. MobX adds non-enumerable symbol properties, which caused parsing to fail. If it's a bug, I can open an issue on GitHub, but if it's intentional, I'll just adjust my expectations 🙂 This test demonstrates the problem.
test('parse record with non-enumerable properties', () => {
const schema = z.record(z.string(), z.number());

const data = {
a: 1,
b: 2,
c: 3,
};

Object.defineProperty(data, Symbol('nonEnumerable'), {
value: 'hidden',
enumerable: false,
});

const parsedWithNonEnumerable = schema.parse(data);
expect(parsedWithNonEnumerable).toEqual({
a: 1,
b: 2,
c: 3,
});
});
test('parse record with non-enumerable properties', () => {
const schema = z.record(z.string(), z.number());

const data = {
a: 1,
b: 2,
c: 3,
};

Object.defineProperty(data, Symbol('nonEnumerable'), {
value: 'hidden',
enumerable: false,
});

const parsedWithNonEnumerable = schema.parse(data);
expect(parsedWithNonEnumerable).toEqual({
a: 1,
b: 2,
c: 3,
});
});
It throws this error on schema.parse(data):
[
{
"code": "invalid_key",
"origin": "record",
"issues": [
{
"expected": "string",
"code": "invalid_type",
"path": [],
"message": "Invalid input: expected string, received symbol"
}
],
"path": [
null
],
"message": "Invalid key in record"
}
]
[
{
"code": "invalid_key",
"origin": "record",
"issues": [
{
"expected": "string",
"code": "invalid_type",
"path": [],
"message": "Invalid input: expected string, received symbol"
}
],
"path": [
null
],
"message": "Invalid key in record"
}
]
1 Reply
Tim Marcus Moore
Tim Marcus MooreOP•4w ago
It passes with import { z } from 'zod/v3' so I suspect this is a bug in v4

Did you find this page helpful?