@gabrielurbina/type-guard

中文文档
0.2.7发布于 2025/11/16MITTypeScriptESM + CJS零依赖近 30 天下载 9135

Type safety for your IO

此软件包已被标记为弃用

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

原始使用文档
文档目录7 节
  1. When to trust your data
  2. Type guards
  3. Guard factories
  4. High order guards
  5. Examples
  6. HTTP responses
  7. Local storage

logo Type Guard GitHub license npm version

Bring Typescript types to your run time

This self contained library will provide you with the tools to move the type validation to the edges of your application, to your IO ring, where you can validate the data coming from outside and trust elsewhere in your application.

When to trust your data

A rather common anti-pattern in JavaScript is to check everywhere in your codebase for a value's type, we'll call this Defensive Programing. It is quite likely that you have come across some code like this:

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;
};

Where a value is checked for its type multiple times across your application, this means that your code doesn't trust its data.

Although Paranoia Oriented Programming might sound cool, it isn't, it is far from productive or even safe.

The application code should be concerned with it's domain, function, modules or classes should not checking if the type of its parameters are valid.

However not all data is safe our code bases should trust internal data, but Must check external data for it might be either malicious, corrupted or just has the wrong format.

This validation should take place in the outermost interfaces of our application what we'll call the IO Layer.

The IO layer exist in different places depending on the application:

  • In libraries or frameworks: the public methods and functions
  • In a server application: HTTP and database requests
  • In a web application: HTTP responses, local-storage and the user's input

Wherever your application meets external data

Performing all the data validation on this layer will allow allow the core application to trust the data is using, allowing you to remove redundant type-checks and unclutter your code.

Type guards

A type guard is a function that checks a value and returns true if the value is of a given type:

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

For example this fuction checks that the unkown value is one valid Grade

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

Naming: Type guards start with is and then the type they check

This library provides these Type-Guards

Guard factories

Guard factories are functions that return a type guard

This library provides these Guard Factories

High order guards

High order guards are functions that receive type-guards and return another type-guard of a composite type:

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

Naming: High order guards start with the base type end with Of

This library provides these High order guards

Examples

HTTP responses

When getting data from your students API type-check it before letting pass into your application:

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
}

Local storage

When getting your user's stored preferences from localStorage type-check it before using it or use some default preferences if the type is invalid or there are no stored preferences:

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 共发布 41 个版本,首次发布于 2020/05/24;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.2.7latest2025/11/1611 个月前
0.2.62025/02/181.7 年前
0.2.52024/06/192 年前
0.2.42023/10/193 年前
0.2.32023/08/283 年前
0.2.22023/07/233 年前

关于 @gabrielurbina/type-guard 的常见问题

@gabrielurbina/type-guard 是什么?

Type safety for your 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。作者已将其标记为弃用,新项目建议寻找替代方案。