/claude-code-superpowers:types-and-interfacesfrom claude-code-superpowers
Teaches Claude Code's type design patterns: discriminated unions for output shapes, Zod schemas as single source of truth for tool inputs, DeepImmutable for AppState, and z.infer to derive TypeScript types from schemas. Apply when designing new types, adding AppState fields, or defining tool input schemas.
Ships in claude-code-superpowers. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Claude Code uses three type patterns consistently: discriminated unions for output data shapes (the Zod outputSchema for tools that can return one of several kinds of result), Zod schemas as single source of truth for tool inputs (the schema drives runtime validation AND TypeScript types simultaneously via z.infer<>), and DeepImmutable wrappers for AppState to prevent accidental mutation.
The discipline is: define shape once, derive everything else. A Zod schema for a tool's input is defined once in inputSchema. The TypeScript type z.infer<typeof inputSchema> is derived from it. The LLM's JSON schema is derived from it. Runtime validation uses it. There is no second interface FooInput to drift from the schema.
The LLM produces JSON. JSON must be validated at runtime. TypeScript types catch compile-time issues. If these are defined separately, they drift: the TypeScript interface says limit?: number but the runtime validator doesn't check it's a number, leading to a crash at runtime. Zod solves this by being both the runtime validator and the source for z.infer<> types.
Discriminated unions for output data types (e.g. a file read that returns text, image, pdf, or unchanged) make exhaustive handling compiler-enforced. The TypeScript compiler narrows the type in each case branch. This eliminates an entire class of missing-case bugs. For errors, tools throw rather than returning an error variant — the success/error boundary is the thrown-exception contract, not the ToolResult shape.
AppState uses DeepImmutable<T> to prevent anyone from mutating state directly. All state changes must go through setAppState(prev => next), making state transitions traceable and atomic.
lazySchema() wrapper from utils/lazySchema.ts to defer parsing until first access (faster startup). Use z.strictObject (not z.object) to reject unknown keys. Derive the TypeScript type with type MyInput = z.infer<typeof inputSchema>.outputSchema using z.discriminatedUnion. Derive the TypeScript type with type Output = z.infer<typeof outputSchema>.AppState type in AppStateStore.ts. The type is DeepImmutable<{...}> — nested objects are also deeply immutable. You cannot .push() to arrays; you must spread them.any: use unknown for values whose type is genuinely unknown at the call site, then narrow with type guards.// Source: src/Tool.ts (ToolResult — tools return data or throw, no error variant)
export type ToolResult<T> = {
data: T
newMessages?: (UserMessage | AssistantMessage | AttachmentMessage | SystemMessage)[]
contextModifier?: (context: ToolUseContext) => ToolUseContext
mcpMeta?: { _meta?: Record<string, unknown>; structuredContent?: Record<string, unknown> }
}
// Tools signal errors by throwing — not by returning { type: 'error' }.
// A successful call returns { data: result }:
return { data: result }
// Source: src/tools/FileReadTool/FileReadTool.ts (discriminated union for output data)
import { lazySchema } from '../../utils/lazySchema.js'
import { z } from 'zod'
// outputSchema uses discriminatedUnion because a file read can yield several kinds of result
const outputSchema = lazySchema(() =>
z.discriminatedUnion('type', [
z.object({
type: z.literal('text'),
file: z.object({ filePath: z.string(), content: z.string(), numLines: z.number() }),
}),
z.object({
type: z.literal('image'),
file: z.object({ filePath: z.string(), /* ... */ }),
}),
z.object({
type: z.literal('pdf'),
file: z.object({ filePath: z.string(), /* ... */ }),
}),
z.object({
type: z.literal('file_unchanged'),
file: z.object({ filePath: z.string() }),
}),
])
)
type OutputSchema = ReturnType<typeof outputSchema>
export type Output = z.infer<OutputSchema>
// TypeScript narrows in each branch — no cast needed:
if (output.type === 'text') {
console.log(output.file.content) // TypeScript knows content: string here
}
// Source: src/tools/FileReadTool/FileReadTool.ts (Zod inputSchema as single source of truth)
// lazySchema() defers parsing until first access — not evaluated at module load
const inputSchema = lazySchema(() =>
z.strictObject({ // strictObject rejects unknown keys
file_path: z.string().describe('The absolute path to the file to read'),
offset: z.number().int().nonnegative().optional()
.describe('Line number to start reading from'),
limit: z.number().int().positive().optional()
.describe('Maximum number of lines to read'),
})
)
type InputSchema = ReturnType<typeof inputSchema>
export type Input = z.infer<InputSchema>
// Equivalent to: { file_path: string; offset?: number; limit?: number }
// Source: src/state/AppStateStore.ts (DeepImmutable AppState)
export type AppState = DeepImmutable<{
settings: SettingsJson
verbose: boolean
tasks: Record<string, TaskState> // DeepImmutable makes this read-only recursively
// ...
}>
// Mutation is impossible:
// state.verbose = true // TypeScript error: cannot assign to read-only property
// Correct: derive new state
context.setAppState(prev => ({ ...prev, verbose: true }))
// Source: src/Task.ts (TaskStatus string literal union)
export type TaskStatus = 'pending' | 'running' | 'completed' | 'failed' | 'killed'
// Exhaustive check in switch is enforced by TypeScript:
function handleStatus(status: TaskStatus) {
switch (status) {
case 'pending': return 'pending'
case 'running': return 'running'
case 'completed': return 'completed'
case 'failed': return 'failed'
case 'killed': return 'killed'
// No default needed — TypeScript knows all cases are covered
}
}
The lazySchema() wrapper deserves attention: Zod schema construction does non-trivial work at parse time (it builds validator functions). Calling it at module load time adds to startup latency. lazySchema() wraps the constructor in a thunk evaluated only on first access, which is typically when the first tool call happens — after startup is already complete.
Before — separate interface and runtime validation that can drift:
// TypeScript type defined separately from runtime validator
interface SearchInput {
query: string
maxResults?: number
caseSensitive?: boolean
}
// Runtime validator defined separately — can drift from the interface above
function validateSearchInput(input: unknown): SearchInput {
if (typeof input !== 'object') throw new Error('Not an object')
if (typeof (input as any).query !== 'string') throw new Error('query must be string')
return input as SearchInput // Dangerous cast
}
After — Zod as single source of truth:
import { lazySchema } from '../../utils/lazySchema.js'
import { z } from 'zod'
// One definition drives both TypeScript types and runtime validation
const inputSchema = lazySchema(() =>
z.strictObject({ // rejects unknown keys — use z.strictObject, not z.object
query: z.string().min(1).describe('Text to search for'),
maxResults: z.number().int().positive().max(1000).optional()
.describe('Maximum number of results (default: 100)'),
caseSensitive: z.boolean().optional()
.describe('Whether to match case exactly (default: false)'),
})
)
// Type derived from schema — no separate interface to maintain
type InputSchema = ReturnType<typeof inputSchema>
type SearchInput = z.infer<InputSchema>
// { query: string; maxResults?: number; caseSensitive?: boolean }
// The schema validates AND types the result — no cast needed
const parsed = inputSchema.parse(rawInput) // throws ZodError if invalid
const safe = inputSchema.safeParse(rawInput) // returns { success, data } or { success: false, error }
outputSchema with a discriminated unionstate.field = value) instead of via setAppStateas any or unsafe type casts appear where Zod validation should be used'left' | 'right') don't need Zod schemas — just use the union directlytool-definition — Zod schemas as inputSchema and outputSchema in the Tool interfaceerror-handling — tools throw for errors; ToolResult carries success data onlydomain-model — AppState's DeepImmutable type shapeWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
16 skills in this plugin
/async-concurrencyTeaches Claude Code's concurrency model: isConcurrencySafe() for parallel tool execution, AbortController propagation for cancellation, Promise.all() for parallel initialization, and the StreamingToolExecutor for concurrent progress streams. Use this when writing tools that could benefit from parallel execution, need to respect cancellation, or must stream partial results. Read-only tools that don't declare concurrency safety are needlessly serialized.
/build-tool-factoryTeaches how to create a new Claude Code tool using the buildTool() factory from src/Tool.ts.
Use this whenever adding a new capability to Claude Code — buildTool is the only correct entry
point. It fills in safe defaults for isConcurrencySafe, isReadOnly, isDestructive,
checkPermissions, and userFacingName so you only implement what your tool actually needs.
/creating-skillsGenerated from the plugin's indexed repository (techymt/claude-code-superpowers) — no native marketplace selected
npx claudepluginhub p/techymt-claude-code-superpowersOther plugins' skills for the same job