Skip to content

Instantly share code, notes, and snippets.

View colinhacks's full-sized avatar

Colin McDonnell colinhacks

View GitHub Profile

Adapted from this recommendation by @jandockx

Cyclical objects

Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop in some cases.

You can protect against cyclical objects starting an infinite loop (at a performance cost) with the following approach (using the above jsonSchema as an example):

gh repo clone https://github.com/colinhacks/live-typescript-monorepo
cd live-typescript-monorepo
cd project-references
pnpm i
code .
# open packages/pkg-b/index.ts
# see Cannot find module 'pkg-a' or its corresponding type declarations
pnpm build # runs `tsc -b`
# restart ts server, "Cannot find module" goes away
pnpm clean # deletes node_modules in all packages
@colinhacks
colinhacks / keybindings.json
Created August 12, 2024 20:25
`goToDefinition` and `navigateBack`
[
{
"key": "cmd+;",
"command": "editor.action.goToDeclaration"
},
{
"key": "shift+cmd+;",
"command": "workbench.action.navigateBack",
"when": "canNavigateBack"
}
@colinhacks
colinhacks / .zshrc
Last active October 25, 2024 03:54
`howto` shell alias for recommending terminal commands
alias howto="gh copilot suggest -t shell"
import * as z from "zod";
const mySchema = z.string();
// there is a global schema registry
z.globalRegistry; // => ZodRegistry<unknown, z.ZodType>
// add schema to registry w/ associated metadata
z.globalRegistry.add(mySchema, { name: "foo", description: "bar" });
// equivalent convenience method (returns mySchema)
@colinhacks
colinhacks / lazy-box.ts
Created December 5, 2024 21:50
Lazy box
function lazy<T>(getter: () => T): { value: T } {
return {
get value() {
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
},
};
}
import { randomString } from "./benchUtil.js";
import { metabench } from "./metabench.js";
export function lazyWithInternalProp<T>(getter: () => T) {
return {
__value: undefined as T,
get value() {
if (this.__value) return this.__value;
const value = getter();
this.__value = value;
@colinhacks
colinhacks / index.ts
Last active April 5, 2025 23:40
Chained `.extend()`
import * as z from "zod";
export const a = z.object({
a: z.string(),
b: z.string(),
c: z.string(),
});
export const b = a.omit({
a: true,