Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Created July 22, 2022 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebinsua/f52cb947e86c844b59e9b54e6d4bc7aa to your computer and use it in GitHub Desktop.
Save sebinsua/f52cb947e86c844b59e9b54e6d4bc7aa to your computer and use it in GitHub Desktop.
import { z } from "zod";
/**
* Approach 1:
*
* Errors with `"Unrecognized key(s) in object: 'readonlyProperty'"`
*/
const s1 = z
.object({
property: z.string(),
})
// This does the work...
.strict();
/**
* @typedef {z.infer<typeof s1>} S1T
*/
const s1_r1 = s1.safeParse({
property: "hello world!",
readonlyProperty: "fail",
});
if (!s1_r1.success) {
console.error("Approach 1:", s1_r1.error);
} else {
console.log("Approach 1:", s1_r1.data);
}
console.log("\n========\n");
const s1_r2 = s1.safeParse({
property: "hello world!",
});
if (!s1_r2.success) {
console.error("Approach 1:", s1_r2.error);
} else {
console.log("Approach 1:", s1_r2.data);
}
console.log("\n========\n");
/**
* Approach 2:
*
* Errors with `"Expected never, received string"`
*/
const s2_inner = z.object({
property: z.string(),
});
const s2 = z.intersection(
s2_inner,
z
.object({
readonlyProperty: z.never(),
})
.partial()
);
/**
* @typedef {z.infer<typeof s2>} S2T
* @typedef {S2T['readonlyProperty']} ReadonlyPropertyType
*/
const s2_r1 = s2.safeParse({
property: "hello world!",
readonlyProperty: "noway",
});
if (!s2_r1.success) {
console.error("Approach 2:", s2_r1.error);
} else {
console.log("Approach 2:", s2_r1.data);
}
console.log("\n========\n");
const s2_r2 = s2.safeParse({
property: "hello world!",
});
if (!s2_r2.success) {
console.error("Approach 2:", s2_r2.error);
} else {
console.log("Approach 2:", s2_r2.data);
}
@sebinsua
Copy link
Author

(Approach 2 doesn't work since there is no way of validating that a property doesn't exist and that if it is set is an error. We've unfortunately allowed it to be undefined above.)

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