百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
O

ow

> 包管理
开源

面向人类的函数参数校验

3.9K stars0 点赞4 次浏览
访问官网GitHub

工具介绍

面向人类的函数参数校验

<br>
<br>

> 为人类设计的函数参数验证

为什么使用 Ow?

TypeScript 仅在编译时验证类型。一旦编译完成,你的程序在运行时仍可能从以下来源接收到意外数据:

  • 接收不可信输入的函数参数
  • CLI 参数和标志
  • 环境变量和配置文件

对于复杂的模式验证(API 响应、数据库查询、JSON 解析),请改用 zod。

Ow 提供的运行时验证能够:

  • 及早捕获错误 - 快速失败,并提供描述性错误信息,而非晦涩难懂的运行时错误
  • 明确预期 - 通过显式声明你的预期,让代码自我文档化
  • 简化调试 - 减少在生产环境中排查类型相关 bug 的时间
  • 随处可用 - 在服务器、浏览器或 CLI 工具中使用相同的验证逻辑
  • 提供类型守卫 - 在验证后收窄 TypeScript 类型,使代码更安全

亮点

  • 富有表现力的链式 API
  • 大量内置验证
  • 支持自定义验证
  • 在 Node.js 中自动推断标签
  • 使用 TypeScript 编写

安装

bash
npm install ow

用法

typescript
import ow from 'ow';

const unicorn = input => {
	ow(input, ow.string.minLength(5));

	// …
};

unicorn(3);
//=> ArgumentError: Expected `input` to be of type `string` but received type `number`

unicorn('yo');
//=> ArgumentError: Expected string `input` to have a minimum length of `5`, got `yo`

实际示例

函数参数

typescript
import ow from 'ow';

const resize = (width: unknown, height: unknown) => {
	ow(width, 'width', ow.number.positive.integer);
	ow(height, 'height', ow.number.positive.integer);
	
	// Process the image...
};

resize(640, 480); // ✓
resize(-100, 200); // ✗ ArgumentError: Expected `width` to be a positive number
resize(640, "480"); // ✗ ArgumentError: Expected `height` to be of type `number`

配置验证

typescript
import ow from 'ow';

const config = {
	port: process.env.PORT,
	apiKey: process.env.API_KEY,
	nodeEnv: process.env.NODE_ENV
};

// 在启动时验证配置
ow(config.port, ow.string.n

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptjavascriptnodejsnpm-packagetype-checking

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类包管理
定价开源

> 相关工具

N
npm
Node.js 默认包管理器
P
pnpm
高效节省磁盘的 Node 包管理器
I
is-gif
Check if a Buffer/Uint8Array is a GIF image