using-typescript-types

15195999826's avatarfrom 15195999826

Guides TypeScript type usage: type vs interface decision, avoiding any, and Zod runtime validation. Use when defining types, choosing type patterns, or validating external data. Triggers: "type vs interface", "any", "unknown", "Zod", "运行时验证", "类型".

⭐0stars🔀0forks📁View on GitHub🕐Updated Jan 9, 2026

When & Why to Use This Skill

This Claude skill acts as a specialized TypeScript architect, enforcing high-standard type safety and runtime validation patterns. It streamlines development by providing clear decision frameworks for 'type vs interface', eliminating unsafe 'any' types through 'unknown' patterns, and ensuring data integrity with Zod-powered runtime schemas. It is designed to improve code maintainability, reduce runtime crashes, and align team coding standards with modern TypeScript best practices.

Use Cases

  • Refactoring legacy TypeScript codebases to replace unsafe 'any' types with 'unknown' and custom type guards for enhanced type safety.
  • Architecting type definitions by choosing between 'type' and 'interface' based on specific needs like declaration merging or class implementation contracts.
  • Implementing robust runtime data validation for API responses, environment variables, and user inputs using Zod schemas to prevent 'silent' data errors.
  • Automating code reviews to ensure all external data sources are properly validated rather than using unsafe type assertions like 'as Type'.
nameusing-typescript-types
description>-
Guides TypeScript type usagetype vs interface decision, avoiding any, and Zod runtime validation.
Triggers"type vs interface", "any", "unknown", "Zod", "运行时验证", "类型".

TypeScript 类型规范

核心约定

规范 项目选择
默认类型定义 type(不用 interface)
未知类型 unknown(禁止 any)
字符串常量 联合类型(不用 enum)
外部数据 Zod 验证(不用 as Type)

Type vs Interface

默认用 type
│
├─ 需要声明合并(扩展第三方库)→ interface
├─ 类的契约(implements)→ interface
└─ 其他情况 → type

禁止 any

// ✗ any
function process(data: any) { }

// ✓ unknown + 类型守卫
function process(data: unknown) {
  if (typeof data === 'string') {
    console.log(data.toUpperCase())
  }
}

// 类型谓词
function isUser(v: unknown): v is User {
  return typeof v === 'object' && v !== null && 'id' in v
}

运行时验证 (Zod)

外部数据必须验证(API、表单、环境变量、配置文件):

import { z } from 'zod'

const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
})

type User = z.infer<typeof UserSchema>

// 验证 API 响应
const user = UserSchema.parse(await res.json())

详细 Zod 模式参见 references/zod-patterns.md