How Do You Validate `unknown` in TypeScript Without a Schema Library? 🛡️
Описание и применение
Проверка unknown в TypeScript без полной схемы: используйте 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