k9 - Hello! I'm getting up to speed. The Comple...
Hello! I'm getting up to speed. The Complex Schema Validation section of zod-tutorial talks about how to preresent what would be a union type in a schema. That doesn't quite do what I'm looking for
I have defined types with a string template type e.g.
which has been a useful way to ensure we don't send the wrong IDs throughout our ecosystem. Those IDs come through JSON schemas I would like to validate with Zod.
I can represent validations (there's already methods that ensure the strings are of their type, e.g.
So, erm, so GameId is everywhere in the codebase, so I have to be careful about refactoring the API. But how can I define a type that a) only accepts a string and b) only if it matches type GameId and c) z.infer() can describe it as type
GameId
?Solution:Jump to solution
Should just be the following:
``ts
type GameId =
g${string}`;
const isGameId = (value: unknown): value is GameId => {...5 Replies
Solution
Should just be the following:
Depending on if you consider just
g
valid, you might want to also have a min length on the string, something along the lines of: z.string().min(2).refine(isGameId)
to make sure you have a string that has g
and at least one character after.
And if your is
function is just for Zod, you can get rid of the string check as well.
There is also
z.custom
which is mentioned in the docs for precisely this use case: https://zod.dev/?id=custom-schemasGitHub
TypeScript-first schema validation with static type inference
TypeScript-first schema validation with static type inference
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Fantastic, wow, thank you!