Как создавать пользовательские Type Guards и что такое `asserts`?
СобеседованиеСужение типов
- Type Predicate:
function isString(x: unknown): x is string { return typeof x === "string" } — сужает тип при true
- Assertion:
function assertString(x: unknown): asserts x is string { if (typeof x !== "string") throw new Error() } — сужает или бросает ошибку
- Condition:
function assert(cond: unknown): asserts cond { if (!cond) throw new Error() } — утверждение инварианта
- Type predicate работает с
.filter(): arr.filter(isNonNull) возвращает массив без null