How Do You Validate `unknown` in TypeScript Without a Schema Library? 🛡️
说明与用途
在 TypeScript 中无需完整模式库即可验证 unknown:使用 is-kit 构建 guard,既能在运行时验证,又能让 TypeScript 进行类型收窄,避免不安全的类型断言。
问题
How to safely turn an unknown value from untrusted boundaries into a usable type without relying on a full schema library?
结果
Runtime guards from is-kit provide lightweight validation that both narrows TypeScript types and ensures runtime safety, eliminating the need for full schema libraries in simple boundary checks.
工作流
- Declare input as
unknown - Define a guard using
is-kitpredicates (e.g.,isString,oneOfValues,struct) - Use the guard in an
ifstatement to narrow the type - Optionally call
safeParseto get a{valid, value}result - Handle invalid cases (e.g., return 400)
- Render or use the validated value
证据
as User changes what the compiler believes. It does not inspect the runtime value.
With is-kit, we can build a guard like this…
safeParse gives us a small tagged result…
- 记录日期: 2026-10-22T02:11:28.990Z