跳转至

Reference: Type Brands

目的:速查 类型品牌(branded types) 和关键类型 关联topics/deep-dive-claude-api.md


1. 概览

Type brands = TypeScript 中模拟 nominal type 的模式。

string ──→ SessionId(防止 string 误用)
number ──→ AgentId
unknown ──→ T(泛型)

用途:编译时类型安全。


2. 5 大类型品牌

2.1 SessionId

// types/ids.ts
export type SessionId = string & { __brand: 'SessionId' }

export function asSessionId(s: string): SessionId {
  return s as SessionId
}

// 用法
const id: SessionId = asSessionId('uuid-string')

session 标识

2.2 AgentId

// types/ids.ts
export type AgentId = string & { __brand: 'AgentId' }

agent 标识

2.3 Uuid

// types/ids.ts
export type Uuid = string & { __brand: 'Uuid' }

UUID 标识

2.4 Path (推测)

export type FilePath = string & { __brand: 'FilePath' }

文件路径

2.5 Url

export type Url = string & { __brand: 'Url' }

URL


3. 4 个关键类型

3.1 Message

type Message = UserMessage | AssistantMessage | ToolResultMessage | SystemMessage

4 种

3.2 Attachment

type Attachment = 
  | FileAttachment
  | CompactFileReferenceAttachment
  | PDFReferenceAttachment
  | AlreadyReadFileAttachment
  | AgentMentionAttachment
  | AsyncHookResponseAttachment
  | HookPermissionDecisionAttachment
  | HookSystemMessageAttachment
  | HookCancelledAttachment
  | HookErrorDuringExecutionAttachment
  | HookSuccessAttachment
  | HookNonBlockingErrorAttachment
  | TeammateMailboxAttachment
  | TeamContextAttachment

14+ 种

3.3 PermissionResult

type PermissionResult = {
  decision: 'allow' | 'deny' | 'ask'
  reason?: string
  rule?: PermissionRule
  // ...
}

3 决策

3.4 PermissionRule

type PermissionRule = {
  tool: string
  // e.g. 'Bash', 'Edit', 'Read'
  pattern?: string
  // e.g. 'git:*', 'rm -rf:*'
}

2 字段


4. 5 个常用工具类型

4.1 Brand<K, T>

type Brand<K, T> = K & { __brand: T }

通用

4.2 Result<T, E>

// 推测
type Result<T, E> = 
  | { ok: true; value: T }
  | { ok: false; error: E }

Result

4.3 Optional<T, K>

type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

Optional

4.4 ReadonlyDeep<T>

type ReadonlyDeep<T> = {
  readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K]
}

深度只读

4.5 AsyncReturnType<T>

type AsyncReturnType<T extends (...args: any[]) => Promise<any>> = 
  T extends (...args: any[]) => Promise<infer R> ? R : never

async 返回


5. 5 个 zod schema 类型

5.1 PluginManifestSchema

// utils/plugins/pluginLoader.ts
const PluginManifestSchema = lazySchema(() => ...)

type PluginManifest = z.infer<typeof PluginManifestSchema>

plugin manifest

5.2 PermissionUpdateSchema

// utils/permissions/PermissionUpdateSchema.ts
const PermissionUpdateSchema = z.object({ ... })

permission update

5.3 HooksConfigSchema

// utils/hooks.ts
const HooksConfigSchema = z.object({ ... })

hooks config

5.4 ToolInputJSONSchema

// Tool.ts
type ToolInputJSONSchema = {
  type: 'object'
  properties?: Record<string, any>
  required?: string[]
  // ...
}

tool input

5.5 ElicitationParamsSchema

// types/hooks.ts
const ElicitRequestURLParamsSchema = z.object({
  url: z.string(),
  // ...
})

elicitation


6. 5 个 union 类型

6.1 InputMode

type InputMode = 'default' | 'bash' | 'plan' | 'voice'  // 推测

输入模式

6.2 PermissionMode

const PERMISSION_MODES = [
  'acceptEdits', 'bypassPermissions', 'default', 'plan', 'auto'
] as const
type PermissionMode = typeof PERMISSION_MODES[number]

5 mode

6.3 HookEventName

type HookEventName = 
  | 'PreToolUse' | 'PostToolUse' 
  | 'SessionStart' | 'SessionEnd'
  | 'Notification' | 'Stop' | 'SubagentStop'
  | 'UserPromptSubmit' | 'PreCompact'

9 事件

6.4 TransportType

type TransportType = 'stdio' | 'sse' | 'http' | 'ws'

4 transport

6.5 TeammateMode

type TeammateMode = 'tmux' | 'in-process' | 'auto'

3 mode


7. 5 个 zustand-style 类型

7.1 AppState

// state/AppStateStore.ts
type AppState = {
  toolPermissionContext: ToolPermissionContext
  verbose: boolean
  mcp: McpState
  plugins: PluginState
  agentDefinitions: AgentDefinitions
  // ... 50+ 字段
}

主 state

7.2 ToolPermissionContext

type ToolPermissionContext = {
  allow: PermissionRule[]
  deny: PermissionRule[]
  ask: PermissionRule[]
  defaultMode: PermissionMode
  // ...
}

permission 上下文

7.3 McpState

type McpState = {
  clients: Record<string, McpClient>
  // ...
}

MCP 状态

7.4 PluginState

type PluginState = {
  enabled: Record<string, LoadedPlugin>
  // ...
}

Plugin 状态

7.5 AgentDefinitions

type AgentDefinitions = {
  activeAgents: Agent[]
  // ...
}

Agent 定义


8. 5 个枚举

8.1 SubscriptionType

type SubscriptionType = 'max' | 'team' | 'team-premium' | 'enterprise' | 'pro'

5 种

8.2 FileOperationType

type FileOperationType = 'read' | 'write' | 'create'

3 种

8.3 HookType

type HookType = 'command' | 'prompt' | 'agent'

3 种

8.4 MCPResultType

type MCPResultType = 'toolResult' | 'structuredContent' | 'contentArray'

3 种

8.5 LogLevel

type LogLevel = 'debug' | 'info' | 'warn' | 'error'

4 级


9. 5 个 type 推断技巧

9.1 z.infer

type PluginManifest = z.infer<typeof PluginManifestSchema>

zod → type

9.2 typeof

const PERMISSION_MODES = [...] as const
type PermissionMode = typeof PERMISSION_MODES[number]

value → type

9.3 ReturnType

type FetchResult = ReturnType<typeof fetchData>

function → type

9.4 Parameters

type FetchParams = Parameters<typeof fetchData>

function params

9.5 Awaited

type Result = Awaited<ReturnType<typeof fetchData>>

Promise unwrap


10. 5 个反模式

10.1 any

// ❌
function f(x: any) { ... }

any

10.2 as any

// ❌
const x = something as any

as any

10.3 @ts-ignore

// ❌
// @ts-ignore

ignore

10.4 复杂 union

// ❌
type X = A & B & C & D & E  // 5 个交叉

太复杂

10.5 嵌套泛型

// ❌
type X = Map<string, Record<string, Array<{ x: number }>>>

嵌套深


11. 速查

// 品牌类型
type Brand<K, T> = K & { __brand: T }

// zod 推断
type X = z.infer<typeof XSchema>

// 函数推断
type Params = Parameters<typeof fn>
type Return = ReturnType<typeof fn>
type Await = Awaited<ReturnType<typeof fn>>

3 速查


12. 总结

类型品牌 = 编译时类型安全

核心: - 5+ 品牌类型(SessionId / AgentId / Uuid / Path / Url) - 14+ Attachment union - 3 决策 union - 5 工具类型 - 5 zod schema

下一步: - 用 Brand<K, T> 包装关键类型 - 用 zod 推断 type - 避免 any / as any