typescript

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TypeScript Development Skill

TypeScript 开发技能

File Organization: This skill uses split structure. See
references/
for advanced patterns and security examples.
文件组织:本技能采用拆分结构。高级模式和安全示例请查看
references/
目录。

1. Overview

1. 概述

This skill provides TypeScript expertise for the JARVIS AI Assistant, ensuring type safety across the entire codebase including Vue components, API routes, 3D rendering, and state management.
Risk Level: MEDIUM - Type system prevents runtime errors, enforces contracts, but misconfiguration can lead to security gaps
Primary Use Cases:
  • Defining type-safe interfaces for JARVIS system data
  • Runtime validation with Zod schemas
  • Generic patterns for reusable HUD components
  • Strict null checking to prevent crashes
本技能为JARVIS AI助手提供TypeScript专业能力,确保整个代码库(包括Vue组件、API路由、3D渲染和状态管理)的类型安全。
风险等级:中等 - 类型系统可防止运行时错误、强制执行契约,但配置错误可能导致安全漏洞
主要用例
  • 为JARVIS系统数据定义类型安全的接口
  • 使用Zod模式进行运行时验证
  • 用于可复用HUD组件的泛型模式
  • 严格的空值检查以防止崩溃

2. Core Responsibilities

2. 核心职责

2.1 Fundamental Principles

2.1 基本原则

  1. TDD First: Write tests before implementation - red, green, refactor
  2. Performance Aware: Apply memoization, lazy loading, and efficient patterns
  3. Strict Mode Always: Enable all strict compiler options - no shortcuts
  4. Explicit Types at Boundaries: Always type function parameters and return values at module boundaries
  5. Runtime Validation: TypeScript types disappear at runtime - use Zod for external data
  6. No Any Escape Hatch: Use
    unknown
    instead of
    any
    , then narrow with type guards
  7. Immutable by Default: Prefer
    readonly
    and
    as const
    for data integrity
  8. Discriminated Unions: Use tagged unions for state machines and error handling
  9. Branded Types: Create nominal types for IDs and sensitive values
  1. 优先TDD:先编写测试再实现功能 - 红、绿、重构
  2. 关注性能:应用记忆化、懒加载和高效模式
  3. 始终启用严格模式:开启所有严格编译选项 - 不找捷径
  4. 边界处显式类型:模块边界的函数参数和返回值必须显式声明类型
  5. 运行时验证:TypeScript类型在运行时会消失 - 对外部数据使用Zod
  6. 禁用Any逃逸舱:使用
    unknown
    替代
    any
    ,然后通过类型守卫收窄类型
  7. 默认不可变:优先使用
    readonly
    as const
    保证数据完整性
  8. 可区分联合类型:为状态机和错误处理使用标记联合类型
  9. 品牌化类型:为ID和敏感值创建标称类型

3. Technology Stack & Versions

3. 技术栈与版本

3.1 Recommended Versions

3.1 推荐版本

PackageVersionSecurity Notes
typescript^5.3.0Latest stable with improved type inference
zod^3.22.0Runtime validation, schema-first
@types/node^20.0.0Match Node.js version
包名版本安全说明
typescript^5.3.0最新稳定版,类型推断能力提升
zod^3.22.0运行时验证,优先使用模式定义
@types/node^20.0.0与Node.js版本匹配

3.2 Compiler Configuration

3.2 编译器配置

json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "exactOptionalPropertyTypes": true,
    "noPropertyAccessFromIndexSignature": true,
    "forceConsistentCasingInFileNames": true,
    "verbatimModuleSyntax": true,
    "moduleResolution": "bundler",
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"]
  }
}
json
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "exactOptionalPropertyTypes": true,
    "noPropertyAccessFromIndexSignature": true,
    "forceConsistentCasingInFileNames": true,
    "verbatimModuleSyntax": true,
    "moduleResolution": "bundler",
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"]
  }
}

4. Implementation Patterns

4. 实现模式

4.1 Branded Types for Security

4.1 用于安全的品牌化类型

typescript
// types/branded.ts
declare const __brand: unique symbol

type Brand<T, B> = T & { [__brand]: B }

// ✅ Prevent accidental mixing of IDs
export type UserId = Brand<string, 'UserId'>
export type SessionId = Brand<string, 'SessionId'>
export type CommandId = Brand<string, 'CommandId'>

// Factory functions with validation
export function createUserId(id: string): UserId {
  if (!/^usr_[a-zA-Z0-9]{16}$/.test(id)) {
    throw new Error('Invalid user ID format')
  }
  return id as UserId
}

// ✅ Type system prevents mixing IDs
function getUser(id: UserId): User { /* ... */ }
function getSession(id: SessionId): Session { /* ... */ }

// This won't compile:
// getUser(sessionId) // Error: SessionId not assignable to UserId
typescript
// types/branded.ts
declare const __brand: unique symbol

type Brand<T, B> = T & { [__brand]: B }

// ✅ 防止ID被意外混用
export type UserId = Brand<string, 'UserId'>
export type SessionId = Brand<string, 'SessionId'>
export type CommandId = Brand<string, 'CommandId'>

// 带验证的工厂函数
export function createUserId(id: string): UserId {
  if (!/^usr_[a-zA-Z0-9]{16}$/.test(id)) {
    throw new Error('无效的用户ID格式')
  }
  return id as UserId
}

// ✅ 类型系统防止ID混用
function getUser(id: UserId): User { /* ... */ }
function getSession(id: SessionId): Session { /* ... */ }

// 以下代码无法编译:
// getUser(sessionId) // 错误:SessionId不能赋值给UserId

4.2 Discriminated Unions for State

4.2 用于状态的可区分联合类型

typescript
// types/jarvis-state.ts

// ✅ Type-safe state machine
type JARVISState =
  | { status: 'idle' }
  | { status: 'listening'; startTime: number }
  | { status: 'processing'; commandId: CommandId }
  | { status: 'responding'; response: string; confidence: number }
  | { status: 'error'; error: JARVISError; retryCount: number }

// ✅ Exhaustive handling
function handleState(state: JARVISState): string {
  switch (state.status) {
    case 'idle':
      return 'Ready'
    case 'listening':
      return `Listening for ${Date.now() - state.startTime}ms`
    case 'processing':
      return `Processing ${state.commandId}`
    case 'responding':
      return `${state.response} (${state.confidence}%)`
    case 'error':
      return `Error: ${state.error.message}`
    default:
      // ✅ Compile-time exhaustiveness check
      const _exhaustive: never = state
      return _exhaustive
  }
}
typescript
// types/jarvis-state.ts

// ✅ 类型安全的状态机
type JARVISState =
  | { status: 'idle' }
  | { status: 'listening'; startTime: number }
  | { status: 'processing'; commandId: CommandId }
  | { status: 'responding'; response: string; confidence: number }
  | { status: 'error'; error: JARVISError; retryCount: number }

// ✅ 穷尽式处理
function handleState(state: JARVISState): string {
  switch (state.status) {
    case 'idle':
      return '就绪'
    case 'listening':
      return `已监听 ${Date.now() - state.startTime}ms`
    case 'processing':
      return `正在处理 ${state.commandId}`
    case 'responding':
      return `${state.response} (置信度 ${state.confidence}%)`
    case 'error':
      return `错误:${state.error.message}`
    default:
      // ✅ 编译时穷尽性检查
      const _exhaustive: never = state
      return _exhaustive
  }
}

4.3 Runtime Validation with Zod

4.3 使用Zod进行运行时验证

typescript
// schemas/command.ts
import { z } from 'zod'

// ✅ Schema-first approach
export const commandSchema = z.object({
  id: z.string().regex(/^cmd_[a-zA-Z0-9]{16}$/),
  action: z.enum(['navigate', 'control', 'query', 'configure']),
  target: z.string().min(1).max(100),
  parameters: z.record(z.unknown()).optional(),
  timestamp: z.number().int().positive(),
  priority: z.number().min(0).max(10).default(5)
})

// ✅ Infer TypeScript type from schema
export type Command = z.infer<typeof commandSchema>

// ✅ Parse with full validation
export function parseCommand(data: unknown): Command {
  return commandSchema.parse(data)
}

// ✅ Safe parse for error handling
export function tryParseCommand(data: unknown): Command | null {
  const result = commandSchema.safeParse(data)
  return result.success ? result.data : null
}
typescript
// schemas/command.ts
import { z } from 'zod'

// ✅ 优先使用模式定义的方式
export const commandSchema = z.object({
  id: z.string().regex(/^cmd_[a-zA-Z0-9]{16}$/),
  action: z.enum(['navigate', 'control', 'query', 'configure']),
  target: z.string().min(1).max(100),
  parameters: z.record(z.unknown()).optional(),
  timestamp: z.number().int().positive(),
  priority: z.number().min(0).max(10).default(5)
})

// ✅ 从模式中推断TypeScript类型
export type Command = z.infer<typeof commandSchema>

// ✅ 带完整验证的解析
export function parseCommand(data: unknown): Command {
  return commandSchema.parse(data)
}

// ✅ 用于错误处理的安全解析
export function tryParseCommand(data: unknown): Command | null {
  const result = commandSchema.safeParse(data)
  return result.success ? result.data : null
}

4.4 Generic Patterns for HUD Components

4.4 用于HUD组件的泛型模式

typescript
// ✅ Generic with constraints - ensures type safety for metrics
interface MetricConfig<T extends Record<string, number>> {
  metrics: T
  thresholds: { [K in keyof T]: { warning: number; critical: number } }
}

type SystemMetrics = { cpu: number; memory: number }
const config: MetricConfig<SystemMetrics> = {
  metrics: { cpu: 45, memory: 72 },
  thresholds: {
    cpu: { warning: 70, critical: 90 },
    memory: { warning: 80, critical: 95 }
  }
}
typescript
// ✅ 带约束的泛型 - 保证指标的类型安全
interface MetricConfig<T extends Record<string, number>> {
  metrics: T
  thresholds: { [K in keyof T]: { warning: number; critical: number } }
}

type SystemMetrics = { cpu: number; memory: number }
const config: MetricConfig<SystemMetrics> = {
  metrics: { cpu: 45, memory: 72 },
  thresholds: {
    cpu: { warning: 70, critical: 90 },
    memory: { warning: 80, critical: 95 }
  }
}

4.5 Type Guards for Narrowing

4.5 用于类型收窄的类型守卫

typescript
// ✅ Type predicate for safe narrowing
function isSuccessResponse<T>(
  response: APIResponse<T>
): response is APIResponse<T> & { success: true; data: T } {
  return response.success && response.data !== undefined
}

// Usage - type automatically narrowed
if (isSuccessResponse(response)) {
  return response.data // ✅ Type is T, not T | undefined
}
typescript
// ✅ 用于安全收窄的类型谓词
function isSuccessResponse<T>(
  response: APIResponse<T>
): response is APIResponse<T> & { success: true; data: T } {
  return response.success && response.data !== undefined
}

// 使用示例 - 类型会自动收窄
if (isSuccessResponse(response)) {
  return response.data // ✅ 类型为T,而非T | undefined
}

4.6 Utility Types for JARVIS

4.6 用于JARVIS的工具类型

typescript
// types/utilities.ts

// ✅ Deep readonly for immutable state
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K]
}

// ✅ Make specific keys required
type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>

// ✅ Extract event payloads
type EventPayload<T> = T extends { payload: infer P } ? P : never

// ✅ Async function return type
type AsyncReturnType<T extends (...args: any[]) => Promise<any>> =
  T extends (...args: any[]) => Promise<infer R> ? R : never
typescript
// types/utilities.ts

// ✅ 用于不可变状态的深度只读类型
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K]
}

// ✅ 使指定字段变为必填
type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>

// ✅ 提取事件负载
type EventPayload<T> = T extends { payload: infer P } ? P : never

// ✅ 异步函数的返回类型
type AsyncReturnType<T extends (...args: any[]) => Promise<any>> =
  T extends (...args: any[]) => Promise<infer R> ? R : never

5. Implementation Workflow (TDD)

5. 实现工作流(TDD)

Step 1: Write Failing Test First

步骤1:先编写失败的测试

typescript
// tests/utils/command-parser.test.ts
import { describe, it, expect } from 'vitest'
import { parseCommand } from '@/utils/command-parser'

describe('parseCommand', () => {
  it('should parse valid command', () => {
    expect(parseCommand('open settings')).toEqual({
      action: 'open', target: 'settings', parameters: {}
    })
  })

  it('should extract parameters', () => {
    expect(parseCommand('set volume to 80')).toEqual({
      action: 'set', target: 'volume', parameters: { value: 80 }
    })
  })

  it('should throw on empty command', () => {
    expect(() => parseCommand('')).toThrow('Command cannot be empty')
  })
})
typescript
// tests/utils/command-parser.test.ts
import { describe, it, expect } from 'vitest'
import { parseCommand } from '@/utils/command-parser'

describe('parseCommand', () => {
  it('应该解析有效的命令', () => {
    expect(parseCommand('open settings')).toEqual({
      action: 'open', target: 'settings', parameters: {}
    })
  })

  it('应该提取参数', () => {
    expect(parseCommand('set volume to 80')).toEqual({
      action: 'set', target: 'volume', parameters: { value: 80 }
    })
  })

  it('空命令应该抛出错误', () => {
    expect(() => parseCommand('')).toThrow('命令不能为空')
  })
})

Step 2: Implement Minimum to Pass

步骤2:编写最小实现使测试通过

Write only code needed to make tests green.
仅编写让测试通过所需的代码。

Step 3: Refactor if Needed

步骤3:按需重构

Improve code quality while keeping tests green.
在保持测试通过的同时提升代码质量。

Step 4: Run Full Verification

步骤4:运行完整验证

bash
npx vitest run              # Unit tests
npx eslint . --ext .ts,.tsx # Linting
npx tsc --noEmit            # Type checking
bash
npx vitest run              # 单元测试
npx eslint . --ext .ts,.tsx # 代码检查
npx tsc --noEmit            # 类型检查

6. Performance Patterns

6. 性能模式

6.1 Memoization

6.1 记忆化

typescript
// ❌ BAD - Recalculates on every render
const processed = data.map(item => heavyTransform(item))

// ✅ GOOD - Memoized computation
import { computed } from 'vue'
const processed = computed(() => data.value.map(item => heavyTransform(item)))
typescript
// ❌ 不良实践 - 每次渲染都重新计算
const processed = data.map(item => heavyTransform(item))

// ✅ 良好实践 - 记忆化计算
import { computed } from 'vue'
const processed = computed(() => data.value.map(item => heavyTransform(item)))

6.2 Lazy Loading

6.2 懒加载

typescript
// ❌ BAD - Loads everything upfront
import { HeavyChart } from '@/components/HeavyChart'

// ✅ GOOD - Lazy load heavy components
import { defineAsyncComponent } from 'vue'
const HeavyChart = defineAsyncComponent(() => import('@/components/HeavyChart'))
typescript
// ❌ 不良实践 - 一次性加载所有内容
import { HeavyChart } from '@/components/HeavyChart'

// ✅ 良好实践 - 懒加载重型组件
import { defineAsyncComponent } from 'vue'
const HeavyChart = defineAsyncComponent(() => import('@/components/HeavyChart'))

6.3 Debounce/Throttle

6.3 防抖/节流

typescript
// ❌ BAD - API call on every keystroke
const handleSearch = (q: string) => fetchResults(q)

// ✅ GOOD - Debounced search (300ms delay)
import { useDebounceFn } from '@vueuse/core'
const debouncedSearch = useDebounceFn((q: string) => fetchResults(q), 300)
typescript
// ❌ 不良实践 - 每次按键都调用API
const handleSearch = (q: string) => fetchResults(q)

// ✅ 良好实践 - 防抖搜索(300ms延迟)
import { useDebounceFn } from '@vueuse/core'
const debouncedSearch = useDebounceFn((q: string) => fetchResults(q), 300)

6.4 Efficient Data Structures

6.4 高效数据结构

typescript
// ❌ BAD - O(n) lookup
const user = users.find(u => u.id === id)

// ✅ GOOD - O(1) lookup with Map
const userMap = new Map(users.map(u => [u.id, u]))
const user = userMap.get(id)

// ✅ GOOD - O(1) membership check with Set
const allowed = new Set(['read', 'write'])
const hasAccess = allowed.has(permission)
typescript
// ❌ 不良实践 - O(n)时间复杂度的查找
const user = users.find(u => u.id === id)

// ✅ 良好实践 - 使用Map实现O(1)时间复杂度的查找
const userMap = new Map(users.map(u => [u.id, u]))
const user = userMap.get(id)

// ✅ 良好实践 - 使用Set实现O(1)时间复杂度的成员检查
const allowed = new Set(['read', 'write'])
const hasAccess = allowed.has(permission)

6.5 Parallel Async Operations

6.5 并行异步操作

typescript
// ❌ BAD - Sequential (total = sum of times)
const user = await fetchUser()
const metrics = await fetchMetrics()

// ✅ GOOD - Parallel (total = max of times)
const [user, metrics] = await Promise.all([fetchUser(), fetchMetrics()])

// ✅ GOOD - With error handling
const results = await Promise.allSettled([fetchUser(), fetchMetrics()])
typescript
// ❌ 不良实践 - 串行执行(总耗时为各操作耗时之和)
const user = await fetchUser()
const metrics = await fetchMetrics()

// ✅ 良好实践 - 并行执行(总耗时为最长操作的耗时)
const [user, metrics] = await Promise.all([fetchUser(), fetchMetrics()])

// ✅ 良好实践 - 带错误处理的并行执行
const results = await Promise.allSettled([fetchUser(), fetchMetrics()])

7. Security Standards

7. 安全标准

7.1 Known Vulnerabilities

7.1 已知漏洞

TypeScript itself has a strong security record. Main risks come from:
Risk AreaDescriptionMitigation
Type ErasureTypes don't exist at runtimeUse Zod for external data validation
Any TypeDisables type checkingEnable noImplicitAny, use unknown
Type AssertionsCan bypass type systemAvoid
as
, use type guards instead
TypeScript本身的安全记录良好。主要风险来自:
风险领域描述缓解措施
类型擦除类型在运行时不存在对外部数据使用Zod验证
Any类型禁用类型检查启用noImplicitAny,使用unknown
类型断言可以绕过类型系统避免使用
as
,改用类型守卫

7.2 OWASP Top 10 Coverage

7.2 OWASP Top 10 覆盖

OWASP CategoryTypeScript Mitigation
A03 InjectionTyped APIs prevent string interpolation in queries
A04 Insecure DesignStrong typing enforces secure interfaces
A08 Software IntegrityCompile-time checks catch errors before deployment
OWASP类别TypeScript缓解措施
A03 注入类型化API防止查询中的字符串插值
A04 不安全设计强类型强制执行安全接口
A08 软件完整性编译时检查在部署前捕获错误

7.3 Secure Type Patterns

7.3 安全类型模式

typescript
// ❌ DANGEROUS - Type assertion bypasses safety
const userData = apiResponse as User

// ✅ SECURE - Runtime validation
const userData = userSchema.parse(apiResponse)

// ❌ DANGEROUS - any disables all checks
function process(data: any) { /* ... */ }

// ✅ SECURE - unknown requires narrowing
function process(data: unknown) {
  const validated = commandSchema.parse(data)
  // Now safely typed
}
typescript
// ❌ 危险 - 类型断言绕过安全检查
const userData = apiResponse as User

// ✅ 安全 - 运行时验证
const userData = userSchema.parse(apiResponse)

// ❌ 危险 - any禁用所有检查
function process(data: any) { /* ... */ }

// ✅ 安全 - unknown需要类型收窄
function process(data: unknown) {
  const validated = commandSchema.parse(data)
  // 现在类型是安全的
}

8. Testing & Quality

8. 测试与质量

typescript
// Type testing with vitest
import { expectTypeOf } from 'vitest'

describe('Type Safety', () => {
  it('should enforce branded types', () => {
    expectTypeOf(createUserId('usr_1234567890123456')).toEqualTypeOf<UserId>()
  })
})

// Schema validation tests
describe('Command Schema', () => {
  it('should reject invalid IDs', () => {
    expect(() => commandSchema.parse({ id: 'invalid' })).toThrow()
  })

  it('should accept valid commands', () => {
    const result = commandSchema.parse({ id: 'cmd_1234567890123456', action: 'query' })
    expect(result.action).toBe('query')
  })
})
typescript
// 使用vitest进行类型测试
import { expectTypeOf } from 'vitest'

describe('类型安全', () => {
  it('应该强制执行品牌化类型', () => {
    expectTypeOf(createUserId('usr_1234567890123456')).toEqualTypeOf<UserId>()
  })
})

// 模式验证测试
describe('命令模式', () => {
  it('应该拒绝无效的ID', () => {
    expect(() => commandSchema.parse({ id: 'invalid' })).toThrow()
  })

  it('应该接受有效的命令', () => {
    const result = commandSchema.parse({ id: 'cmd_1234567890123456', action: 'query' })
    expect(result.action).toBe('query')
  })
})

9. Common Mistakes & Anti-Patterns

9. 常见错误与反模式

9.1 Critical Security Anti-Patterns

9.1 严重安全反模式

Never: Use Type Assertions for External Data

绝对不要:对外部数据使用类型断言

typescript
// ❌ DANGEROUS - No runtime validation
const user = JSON.parse(data) as User

// ✅ SECURE - Validate at runtime
const user = userSchema.parse(JSON.parse(data))
typescript
// ❌ 危险 - 无运行时验证
const user = JSON.parse(data) as User

// ✅ 安全 - 运行时验证
const user = userSchema.parse(JSON.parse(data))

Never: Ignore Null/Undefined Checks

绝对不要:忽略空值/未定义检查

typescript
// ❌ DANGEROUS - Runtime crash if undefined
function getConfig(key: string) {
  return config[key].value  // May be undefined!
}

// ✅ SECURE - Explicit null handling
function getConfig(key: string): string | undefined {
  return config[key]?.value
}
typescript
// ❌ 危险 - 如果值为undefined会导致运行时崩溃
function getConfig(key: string) {
  return config[key].value  // 可能为undefined!
}

// ✅ 安全 - 显式空值处理
function getConfig(key: string): string | undefined {
  return config[key]?.value
}

Never: Use Index Signatures Without Checks

绝对不要:不检查就使用索引签名

typescript
// ❌ DANGEROUS - No type safety
const handlers: Record<string, Handler> = {}
handlers['cmd'].execute()  // May be undefined!

// ✅ SECURE - Explicit lookup with check
const handler = handlers['cmd']
if (handler) {
  handler.execute()
}
typescript
// ❌ 危险 - 无类型安全
const handlers: Record<string, Handler> = {}
handlers['cmd'].execute()  // 可能为undefined!

// ✅ 安全 - 显式查找并检查
const handler = handlers['cmd']
if (handler) {
  handler.execute()
}

9.2 Performance Anti-Patterns

9.2 性能反模式

Avoid: Excessive Type Complexity

避免:过度复杂的类型

typescript
// ❌ BAD - Unreadable, slow compilation
type DeepPartialRecord<T> = T extends object
  ? { [K in keyof T]?: DeepPartialRecord<T[K]> }
  : T extends Array<infer U>
  ? Array<DeepPartialRecord<U>>
  : T

// ✅ GOOD - Simple, clear types
interface PartialConfig {
  theme?: Partial<ThemeConfig>
  metrics?: Partial<MetricsConfig>
}
typescript
// ❌ 不良实践 - 难以阅读,编译缓慢
type DeepPartialRecord<T> = T extends object
  ? { [K in keyof T]?: DeepPartialRecord<T[K]> }
  : T extends Array<infer U>
  ? Array<DeepPartialRecord<U>>
  : T

// ✅ 良好实践 - 简洁清晰的类型
interface PartialConfig {
  theme?: Partial<ThemeConfig>
  metrics?: Partial<MetricsConfig>
}

10. Pre-Deployment Checklist

10. 部署前检查清单

Phase 1: Before Writing Code

阶段1:编写代码前

  • Write failing tests first (TDD)
  • Define types and interfaces for new features
  • Plan Zod schemas for external data
  • Identify performance-critical paths
  • Review existing patterns in codebase
  • 先编写失败的测试(TDD)
  • 为新功能定义类型和接口
  • 为外部数据规划Zod模式
  • 识别性能关键路径
  • 审查代码库中的现有模式

Phase 2: During Implementation

阶段2:实现过程中

  • strict: true
    enabled in tsconfig
  • noUncheckedIndexedAccess: true
    enabled
  • noImplicitAny: true
    enabled
  • No
    any
    types in production code
  • All external data validated with Zod
  • Branded types for sensitive IDs
  • Discriminated unions for state machines
  • Memoization applied to expensive computations
  • Lazy loading for heavy components
  • Efficient data structures (Map/Set) for lookups
  • tsconfig中启用
    strict: true
  • 启用
    noUncheckedIndexedAccess: true
  • 启用
    noImplicitAny: true
  • 生产代码中无
    any
    类型
  • 所有外部数据均使用Zod验证
  • 敏感ID使用品牌化类型
  • 状态机使用可区分联合类型
  • 对昂贵计算应用记忆化
  • 重型组件使用懒加载
  • 查找操作使用高效数据结构(Map/Set)

Phase 3: Before Committing

阶段3:提交代码前

  • All tests pass (
    npx vitest run
    )
  • No linting errors (
    npx eslint .
    )
  • No TypeScript errors (
    npx tsc --noEmit
    )
  • All API inputs validated at runtime
  • No type assertions on external data
  • Performance patterns applied where needed
  • 所有测试通过(
    npx vitest run
  • 无代码检查错误(
    npx eslint .
  • 无TypeScript错误(
    npx tsc --noEmit
  • 所有API输入均在运行时验证
  • 不对外部数据使用类型断言
  • 必要处应用性能模式

11. Summary

11. 总结

TypeScript provides compile-time safety for JARVIS development:
  1. Strict Configuration: Enable all strict options for maximum safety
  2. Runtime Validation: Types disappear at runtime - use Zod
  3. Branded Types: Prevent mixing of IDs and sensitive values
  4. Type Guards: Safely narrow
    unknown
    data with predicates
Remember: TypeScript only checks at compile time. Every boundary with external data must have runtime validation.

References:
  • references/advanced-patterns.md
    - Complex type patterns
  • references/security-examples.md
    - Secure typing practices
TypeScript为JARVIS开发提供编译时安全保障:
  1. 严格配置:启用所有严格选项以获得最大安全性
  2. 运行时验证:类型在运行时会消失 - 使用Zod
  3. 品牌化类型:防止ID和敏感值被混用
  4. 类型守卫:使用谓词安全收窄
    unknown
    数据
注意:TypeScript仅在编译时进行检查。所有与外部数据交互的边界都必须进行运行时验证。

参考资料:
  • references/advanced-patterns.md
    - 复杂类型模式
  • references/security-examples.md
    - 安全类型实践