This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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.)