type User = {
id: string
email: string
age: number
}
// прямо из сети — без проверки
const user: User =
await fetch('/api/me').then(r => r.json())// валидатор t12n, скомпилирован из User
function checkUser(v) {
if (typeof v.id !== 'string') fail('id')
if (typeof v.email !== 'string') fail('email')
if (typeof v.age !== 'number') fail('age')
return v
}
// граница теперь под охраной
const user = checkUser(
await fetch('/api/me').then(r => r.json())
)type Order = {
id: string
total: number
status: 'paid' | 'pending'
}
// восстановлено из localStorage — без проверки
const order: Order =
JSON.parse(localStorage.cart)// валидатор t12n, скомпилирован из Order
function checkOrder(v) {
if (typeof v.id !== 'string') fail('id')
if (typeof v.total !== 'number') fail('total')
if (v.status !== 'paid' &&
v.status !== 'pending') fail('status')
return v
}
const order = checkOrder(
JSON.parse(localStorage.cart)
)type Message = {
kind: string
data: number[]
}
// пришло через postMessage — без проверки
const msg: Message = event.data// валидатор t12n, скомпилирован из Message
function checkMessage(v) {
if (typeof v.kind !== 'string') fail('kind')
if (!Array.isArray(v.data)) fail('data')
for (const n of v.data)
if (typeof n !== 'number') fail('data[]')
return v
}
const msg = checkMessage(event.data)