# @gabrielurbina/type-guard 中文文档

规范地址：https://npmcn.com/package/%40gabrielurbina/type-guard/

版本：0\.2\.7
npm 元数据更新时间：2026-03-27T06:42:56.081Z
中文译文更新时间：2026-11-15T20:45:54.049Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gabrielurbina/type-guard
原文对照：https://npmcn.com/package/%40gabrielurbina/type-guard/?lang=original
项目主页：https://github.com/gabrielricardourbina/type-guard#readme
源码仓库：https://github.com/gabrielricardourbina/type-guard

弃用说明：Package no longer supported\. Contact Support at https://www\.npmjs\.com/support for more info\.

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：90.8 kB，126 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2020-05-24T09:22:56.151Z
- 最新版本发布：2025-11-16T09:11:21.691Z
- 近 30 天下载量：9135（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：41（近 12 个月 1 个）

## 中文简介

输入您的 IO 的安全性

## 安装

```sh
npm install @gabrielurbina/type-guard
```

也可以使用：`pnpm add @gabrielurbina/type-guard`、`yarn add @gabrielurbina/type-guard`、`bun add @gabrielurbina/type-guard`

## README

# ![logo](https://raw.githubusercontent.com/gabrielricardourbina/type-guard/master/logo.svg) 类型警卫 [![GitHub license](https://img.shields.io/npm/l/@gabrielurbina/type-guard?color=%232a7e7d&style=flat-square)](https://github.com/gabrielricardourbina/type-guard/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/@gabrielurbina/type-guard?color=%232a7e7d&style=flat-square)](https://www.npmjs.com/package/@gabrielurbina/type-guard)

_将类型带入运行时间_

此自封自封库将为您提供工具, 将类型验证移动到您的应用程序边缘, 移动到您的 IO 环上, 您可以在此验证来自外部的数据, 并信任其它应用程序 .

## 何时相信你的数据

在JavaScript中,一个相当常见的反模式是检查你代码库中的每一处一个值的类型,我们叫这个 **防御程序**。 。 。 . 很可能你遇到这样的密码:

```javascript
const someFunction = (value) => {
    if (value !== undefined) throw Error("value must be defined");
    return anotherFunction(value, "I already checked value")
};
const anotherFunction = (value, message) => {
    if (value !== undefined) throw Error("value must be defined");
    return value + message;
};
```

当在您的应用程序中多次检查其类型时,这意味着 _**您的代码不相信它的数据**_。 。 。 .

虽然 **偏执编程** 听起来可能很酷,它不是, 它远远没有生产,甚至安全.

应用程序代码应当关注其域名,功能,模块或类不应检查其参数类型是否有效.

不过 _**并非所有数据都是安全的**_ 我们的代码基础应该信任内部数据,但 **必须** 请检查外部数据是否为恶意、腐败或只是格式错误.

校验应在我们应用程序的最外层接口中进行 **IO 层**。 。 。 .

IO层依应用程序的不同而存在于不同的地方:

-   在图书馆或框架中:公共方法和职能
-   在服务器应用程序中: HTTP 和数据库请求
-   在网络应用程序中: HTTP 响应,本地存储和用户输入

应用程序与外部数据相接之处

在此层上进行所有的数据验证将允许核心应用程序信任数据正在使用,允许您删除冗余的类型检查并解开您的代码 .

## 类型警卫

类型守护是检查值并返回的函数 _真实_ 如果值为特定类型:

```typescript
type Guard<T extends V, V = unknown> = (v: V) => v is T;
```

例如, 此虚构检查显示未定义的值是有效的 `Grade`

```typescript
type Grade = "A" | "B" | "C" | "D" | "F"; 
const isGrade = (value: unknown): value is Grades =>  ["A","B","C","D","F"].includes(value)
```

_命名_: 类型警卫从 **实值** 然后检查类型

[**此库提供这些类型守护**](https://npmcn.com/package/%40gabrielurbina/type-guard/modules.md#guard-functions)

## 警卫工厂

警卫工厂是用来送回一类警卫的

[**这个图书馆提供这些护卫工厂**](https://npmcn.com/package/%40gabrielurbina/type-guard/modules.md#guard-factory-functions)

## 高级警卫

高阶卫士是接收类型卫士并返回复合类型的另一个类型卫士的功能:

```typescript
const ArrayOf= <T>(type: Guard<T>) => {
    return (arr: unknown): arr is Array<T> => Array.isArray(arr) && arr.every((v) => type(v));
};
```

_命名_: 高命令卫士从基底类型起首,以 **员额**

[**这个图书馆提供这些高档警卫**](https://npmcn.com/package/%40gabrielurbina/type-guard/modules.md#high-order-guard-functions)

## 实例

### HTTP 回复

当从学生中获取数据时, API 在允许输入应用程序前进行类型检查 :

```typescript
import { ArrayOf, ObjectOf, isString, isNumber, isBoolean } from "@gabrielurbina/type-guard";

type Student = { firstName: string; lastName: string; age: number; active: boolean };

const isStudent = ObjectOf({
   firstName: isString,
   lastName: isString,
   age: isNumber,
   active: isBoolean
});

const isStudentList = ArrayOf([isStudent]);

export const fetchStudents = async (id: string): Promise<Student[]> => {
   // Remember to treat external data as unknown
   const response: unknown = await(await fetch(`api/students?class=${id}`)).json();
   if(!isStudentList(response)) throw Error("Invalid API response");
   return response
}
```

### 本地存储

当获得用户存储的首选项时 `localStorage` 如果类型无效或没有存储偏好,则在使用它之前先检查它或使用一些默认偏好 :

```typescript
import { ObjectOf, ValueOf, isNumber, isBoolean } from "@gabrielurbina/type-guard";

type Theme = "dark" | "light";
type Currency = "USD" | "EUR" | "GBP";

interface UserPreferences {
   theme: Theme;
   currency: Currency;
   timeZoneOffset: number;
   finishedWalkthrough: boolean;
};

const isUserPreferences = ObjectOf({
   theme: ValueOf<Theme>(["dark" , "light"]),
   currency: ValueOf<Currency>(["USD" , "EUR" , "GBP"]),
   timeZoneOffset: isNumber,
   finishedWalkthrough: isBoolean,
});

const defaultUserPreferences: UserPreferences = {
   theme: "light",
   currency: "USD",
   timeZoneOffset: 0,
   finishedWalkthrough: false,
}

export const retrieveUserPreferences = (): UserPreferences => {
   const storedPreferences = localStorage.getItem("user-preferences");
   if (storedPreferences === null) return defaultUserPreferences;
   // Treat external data as unknown
   const preferences: unknown = JSON.parse(storedPreferences);
   if(!isUserPreferences(preferences)) return defaultUserPreferences;
   return preferences;
}
```

## 常见问题

### @gabrielurbina/type-guard 是什么？

输入您的 IO 的安全性注意：该包已被作者标记为弃用——Package no longer supported\. Contact Support at https://www\.npmjs\.com/support for more info\.

### 如何安装 @gabrielurbina/type-guard？

在项目目录运行 npm install @gabrielurbina/type-guard，或使用 pnpm add / yarn add / bun add。

### @gabrielurbina/type-guard 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gabrielurbina/type-guard 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @gabrielurbina/type-guard 可以商用吗？

@gabrielurbina/type-guard 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gabrielurbina/type-guard 的下载量有多少？

根据 npm 官方下载统计，@gabrielurbina/type-guard 在 2026/10/16 – 2026/11/14 这 30 天内被下载 9,135 次，日均约 305 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gabrielurbina/type-guard 还在维护吗？

最新版本 0\.2\.7 发布于 2025/11/16（11 个月前）；至今共发布 41 个版本，其中过去 12 个月发布了 1 个；首次发布于 2020/05/24。作者已将其标记为弃用，新项目建议寻找替代方案。

