{"content":"# Assertion Helper\n\nTypeScript assertion function for runtime type narrowing with descriptive error messages. Based on tiny-invariant.\n\n**Install via shadcn registry:**\n\n```bash\nbunx --bun shadcn@latest add https://fullstackrecipes.com/r/assert.json\n```\n\n**Or copy the source code:**\n\n`lib/common/assert.ts`:\n\n```typescript\nconst prefix: string = \"Assertion failed\";\n\n/**\n * TypeScript assertion function that narrows types when condition is truthy.\n * Throws if condition is falsy. Message can be string or lazy function.\n */\nexport default function assert(\n  condition: any,\n  message?: string | (() => string),\n): asserts condition {\n  if (condition) {\n    return;\n  }\n\n  const provided: string | undefined =\n    typeof message === \"function\" ? message() : message;\n  const value: string = provided ? `${prefix}: ${provided}` : prefix;\n  throw new Error(value);\n}\n```\n\n### Why This Pattern?\n\n- **Type narrowing**: TypeScript understands the assertion and narrows types after the check\n- **Descriptive errors**: Know exactly what assertion failed and why\n- **Lazy messages**: Defer expensive message construction until failure occurs\n\n### Usage\n\nThe `assert` function throws if the condition is falsy, and narrows the type when it passes:\n\n```typescript\nimport assert from \"@/lib/common/assert\";\n\nfunction processUser(user: User | null) {\n  assert(user, \"User must exist\");\n  // TypeScript now knows `user` is `User`, not `User | null`\n  console.log(user.name);\n}\n```\n\n### Lazy Message Evaluation\n\nFor expensive message construction, pass a function that only runs on failure:\n\n```typescript\nassert(\n  TOOL_TYPES.includes(part.type as ToolType),\n  () => `Invalid tool type: ${part.type}`,\n);\n```\n\n---\n\n### Attribution\n\nThis implementation is based on [tiny-invariant](https://www.npmjs.com/package/tiny-invariant).\n\n---\n\n## References\n\n- [TypeScript Assertion Functions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions)\n- [tiny-invariant](https://www.npmjs.com/package/tiny-invariant)"}