mcpField
R
runtime-type-reconstruction

runtime-type-reconstruction

github.com/marius-townhouse开发644 次安装38 周前更新
代码仓库

关于 runtime-type-reconstruction

这项 TypeScript 技能介绍如何使用 io-ts、zod 或 runtypes 等模式库验证运行时数据,适合需要运行时检查并从同一模式获得静态类型的开发者。

主要功能

  1. 01在运行时验证数据
  2. 02以类型安全方式解析 JSON
  3. 03使用 io-ts、zod 或 runtypes 定义模式
  4. 04从模式获得静态类型

适用场景

  1. 01检查外部数据是否符合预期结构
  2. 02安全解析 JSON
  3. 03构建验证模式
  4. 04使运行时验证与 TypeScript 类型保持一致

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/marius-townhouse/effective-typescript-skills --skill runtime-type-reconstruction

安装后在 Claude Code 中输入/runtime-type-reconstruction确认已加载。

详细介绍

了解如何在运行时重建类型

概述

TypeScript 类型会在运行时被擦除,但有时你需要验证运行时数据是否符合你的类型。使用 io-ts、zod 或 runtypes 等库来定义架构,同时提供运行时验证和静态类型。这样可以确保类型与实际数据相符。

何时使用此技能

  • 在运行时验证数据
  • 以类型安全的方式解析 JSON
  • 类型需要运行时检查
  • 使用 io-ts、zod 或 runtypes
  • 构建验证架构

铁律

使用 zod 或 io-ts 等验证库,从单一事实来源同时获得运行时验证和 TypeScript 类型。

使用 Zod 的示例

import { z } from 'zod';

// Define schema once
const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
  age: z.number().optional(),
});

// Get TypeScript type from schema
type User = z.infer<typeof UserSchema>;

// Runtime validation
const result = UserSchema.safeParse(unknownData);
if (result.success) {
  // result.data is typed as User
  console.log(result.data.name);
} else {
  console.error(result.error);
}

参考资料

  • Dan Vanderkam 著《Effective TypeScript》第 2 版
  • 条目 74:了解如何在运行时重建类型

评论

支持 Markdown