面向人类的函数参数校验
<br>
<br>
TypeScript 仅在编译时验证类型。一旦编译完成,你的程序在运行时仍可能从以下来源接收到意外数据:
对于复杂的模式验证(API 响应、数据库查询、JSON 解析),请改用 zod。
Ow 提供的运行时验证能够:
npm install owimport 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`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`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,或尚未同步最近议题。