Strict object validation is handy for data exploration
Published on in JavaScript, TypeScript and Zod
Alternative title:
I finally found a good use case for z.object().strict()
in Zod.
Zod's z.object()
ignores unknown keys (= object keys not specified in a Zod schema) by default.
Unknown keys can be disallowed with Zod's .strict()
method.
When would .strict()
be useful?
From a GitHub comment by Kamil Trebunia:
For consuming APIs I would almost always pick
z.object
, but for data exploration as I am doing nowz.strictObject
is necessary and I am glad I found about it.
So: if you are exploring what data a poorly documented API returns,
you can use z.object().strict()
(or the shorthand z.strictObject()
)
to avoid missing any keys;
unspecified keys will make Zod throw an error,
so you can adjust the Zod schema accordingly.
There's no .deepStrict()
method in Zod,
but it's easy to search for .object(
and replace all occurrences with .strictObject(
.