Loading page...Загружаем страницу...正在加载页面...
AtlasRepo

Validate `unknown` in TypeScript Without a Schema Library

说明与用途

如何使用 is-kit 断言安全地将 unknown 值转换为可用类型,而无需完整的模式库。

问题

How to safely convert an unknown value from untrusted boundaries into a usable type without relying on a full schema library?

结果

Using is-kit guards provides a lightweight, composable way to validate unknown values, giving both runtime safety and TypeScript narrowing without the overhead of a full schema library.

工作流

  • Declare input: unknown from an untrusted source.
  • Import is-kit predicates (isString, oneOfValues, struct, etc.).
  • Define a guard, e.g., const isUser = struct({id: isString, name: isString, role: oneOfValues("admin","member")});
  • Use the guard: if (isUser(input)) { /* input is now narrowed */ }
  • Optionally use safeParse(isUser, input) to get a {valid, value} result for control flow.
  • Handle invalid cases by returning an error response or similar.
  • Render or process 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…

来源

safeJsonParse…

来源

  • 记录日期: 2026-10-15T00:55:57.971Z