Skip to content
Myr

utils.ts

This file

Path

src/validator/utils.ts

69 lines · 2.1 KiB · TypeScript

Last changed by

fix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03

History of this file

Take it

fix(validator): preserve literal union types in input type inference (#4583)Yusuke Wadabefore adoptionbde9a03

lines 1–69why, one step back
1import type { FormValue, ParsedFormValue, ValidationTargets } from '../types'
2import type { UnionToIntersection } from '../utils/types'34/**5 * Checks if T is a literal union type (e.g., 'asc' | 'desc')6 * that should be preserved in input types.7 * Returns true for union literals, false for single literals or wide types.8 */9export type IsLiteralUnion<T, Base> = [Exclude<T, undefined>] extends [Base]10 ? [Exclude<T, undefined>] extends [UnionToIntersection<Exclude<T, undefined>>]11 ? false12 : true13 : false1415// Check if type is an optional union (T | undefined) but not unknown/any16type IsOptionalUnion<T> = [unknown] extends [T]17 ? false // unknown or any18 : undefined extends T19 ? true20 : false2122// Helper to force TypeScript to expand type aliases23type SimplifyDeep<T> = { [K in keyof T]: T[K] } & {}2425type InferInputInner<26 Output,27 Target extends keyof ValidationTargets,28 T extends FormValue,29> = SimplifyDeep<{30 [K in keyof Output]: IsLiteralUnion<Output[K], string> extends true31 ? Output[K]32 : IsOptionalUnion<Output[K]> extends true33 ? Output[K]34 : Target extends 'form'35 ? T | T[]36 : Target extends 'query'37 ? string | string[]38 : Target extends 'param'39 ? string40 : Target extends 'header'41 ? string42 : Target extends 'cookie'43 ? string44 : unknown45}>4647/**48 * Utility type to infer input types for validation targets.49 * Preserves literal union types (e.g., 'asc' | 'desc') while using50 * the default ValidationTargets type for other values.51 *52 * @example53 * ```ts54 * // In @hono/zod-validator or similar:55 * type Input = InferInput<z.input<Schema>, 'query'>56 * // { orderBy: 'asc' | 'desc', page: string | string[] }57 * ```58 */59export type InferInput<60 Output,61 Target extends keyof ValidationTargets,62 T extends FormValue = ParsedFormValue,63> = [Exclude<Output, undefined>] extends [never]64 ? {}65 : [Exclude<Output, undefined>] extends [object]66 ? undefined extends Output67 ? SimplifyDeep<InferInputInner<Exclude<Output, undefined>, Target, T>> | undefined68 : SimplifyDeep<InferInputInner<Output, Target, T>>69 : {}