UNPKG

hi-guardian

Version:

Runtime type guard generator for TypeScript. Create validators for objects, arrays, tuples and unions with automatic type inference. 3x faster than io-ts with zero dependencies.

42 lines (37 loc) 1.76 kB
type TypeGuardConfig<T extends object> = { [key in keyof T]: (value: unknown) => value is T[key]; }; /** * author: 杜朝辉 * date: 2025-02-28 * @param config 类型守卫配置对象(键为属性名,值为类型验证函数) * @returns 类型守卫函数 */ declare function createObjTypeGuard<T extends object>(config: TypeGuardConfig<T>): (obj: unknown) => obj is T; type ArrayTypeGuardConfig<T> = (value: unknown) => value is T; /** * 创建数组类型守卫函数 * @param elementGuard 数组元素类型验证函数 * @returns 类型守卫函数,判断是否为指定类型的数组 */ declare function createArrayTypeGuard<T>(elementGuard: ArrayTypeGuardConfig<T>): (arr: unknown) => arr is T[]; type TupleTypeGuardConfig<T extends any[]> = { [Index in keyof T]: (value: unknown) => value is T[Index]; }; /** * author: 杜朝辉 * date: 2025-02-19 * description: 创建元组守卫 * @param config - 元组类型验证配置数组(每个元素对应元组位置的类型验证函数) * @param requiredIndices - 可选参数,必选元素的索引数组(默认所有元素必选) * @returns 类型守卫函数 */ declare function createTupleTypeGuard<T extends any[]>(config: TupleTypeGuardConfig<T>, requiredIndices?: number[]): (tuple: unknown) => tuple is T; type UnionTypeGuardConfig<T> = Array<(value: unknown) => value is T>; /** * 创建联合类型守卫函数 * @param config - 联合类型验证配置数组(每个函数对应一种可能的类型) * @returns 类型守卫函数 */ declare function createUnionTypeGuard<T>(config: UnionTypeGuardConfig<T>): (value: unknown) => value is T; export { createArrayTypeGuard, createObjTypeGuard, createTupleTypeGuard, createUnionTypeGuard };