@dloizides/ utils (英语)
TypeScript 项目的类型安全公用功能
安装
npm install @dloizides/utils
# or
yarn add @dloizides/utils
# or
pnpm add @dloizides/utils
特征
- 类型警卫数字 :
isValueDefined, (中文(简体) ),isNotEmptyArray, (中文(简体) ),isNotEmptyString, (中文(简体) ),isNullOrUndefined, (中文(简体) ),isEmptyArray, (中文(简体) ),isEmptyString - 请求数字 :
assertDefined - 无依赖: 无运行时间依赖性
- 树能震动: 只导入您需要的东西
- 类型脚本第一: 完全类型推论并缩小范围
使用量
类型警卫
import { isValueDefined, isNotEmptyArray, isNotEmptyString } from '@dloizides/utils';
// isValueDefined - Check if value is not null or undefined
const user = getUserOrNull();
if (isValueDefined(user)) {
console.log(user.name); // TypeScript knows user is defined
}
// isNotEmptyArray - Check if array has elements
const items = getItems();
if (isNotEmptyArray(items)) {
console.log(items[0]); // Safe to access first element
}
// isNotEmptyString - Check if string has content
const input = formData.get('name');
if (isNotEmptyString(input)) {
saveUser(input); // String is guaranteed to have content
}
请求
import { assertDefined } from '@dloizides/utils';
function processUser(user: User | null) {
assertDefined(user, 'User is required');
// user is now narrowed to User
return user.name.toUpperCase();
}
子路径导入
// Import only guards
import { isValueDefined } from '@dloizides/utils/guards';
// Import only assertions
import { assertDefined } from '@dloizides/utils/assertions';
API 参考
类型警卫
| 函数 | 说明 |
|---|---|
isValueDefined<T>(value) | 回返 true 如果数值不是 null 或者说 undefined |
isNotEmptyArray<T>(value) | 回返 true 如果值是长度大于0的数组 |
isNotEmptyString(value) | 回返 true 如果值是非空字符串( 修剪后) |
isNullOrUndefined(value) | 回返 true 如果值是 null 或者说 undefined |
isEmptyArray(value) | 回返 true 如果值是一个空数组 |
isEmptyString(value) | 回返 true 如果数值是空的或空白的 |
请求
| 函数 | 说明 |
|---|---|
assertDefined<T>(value, message?) | 如果值为 null 或者说 undefined |
许可证
麻省理工学院