Validate `unknown` in TypeScript Without a Schema Library
Описание и применение
Как безопасно преобразовать значение unknown из ненадёжных источников в тип, используя is-kit‑гварды, без полной схемы валидации.
Задача
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: unknownfrom an untrusted source. - Import
is-kitpredicates (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