shield()
We use shield()
to assert telefunction arguments;
as we have seen in the Telefunc Tour,
telefunctions are public and need protection.
See Guides > TypeScript > shield()
.
Examples showcasing the most common shield()
types:
// TodoList.telefunc.js
// Environment: Node.js
import { shield } from 'telefunc'
const t = shield.type
shield(onTextChange, [t.number, t.string])
async function onTextChange(id, text) {
// typeof id === 'number'
// typeof text === 'string'
}
shield(onCompletedToggle, [{ id: t.number, isCompleted: t.boolean }])
async function onCompletedToggle({ id, isCompleted }) {
// typeof id === 'number'
// typeof isCompleted === 'boolean'
}
shield(onTagListChange, [t.array(t.string)])
async function onTagListChange(tagList) {
// tagList.every(tagName => typeof tagName === 'string')
}
shield(onNewMilestone, [{
name: t.string,
deadline: t.nullable(t.date),
ownerId: t.optional(t.number)
}])
async function onNewMilestone({ name, deadline, ownerId }) {
// typeof name === 'string'
// deadline === null || deadline.constructor === Date
// ownerId === undefined || typeof ownerId === 'number'
}
shield(onStatusChange, [t.or(
t.const('DONE'),
t.const('PROGRESS'),
t.const('POSTPONED')
)])
async function onStatusChange(status) {
// status === 'DONE' || status === 'PROGRESS' || status === 'POSTPONED'
}
List of shield()
types:
const t = shield.type | TypeScript | JavaScript |
---|---|---|
t.string | string | typeof value === 'string' |
t.number | number | typeof value === 'number' |
t.boolean | boolean | value === true || value === false |
t.date | Date | value.constructor === Date |
t.array(T) | T[] | value.every(element => isT(element)) |
t.object(T) | Record<string, T> | Object.values(value).every(v => isT(v)) |
{ k1: T1, k2: T2, ... } | { k1: T1, k2: T2, ... } | isT1(value.k1) && isT2(value.k2) && ... |
t.or(T1, T2, ...) | T1 | T2 | ... | isT1(value) || isT2(value) || ... |
t.tuple(T1, T2, ...) | [T1, T2, ...] | isT1(value[0]) && isT2(value[1]) && ... |
t.const(val) | val as const | value === val |
t.optional(T) | T | undefined | isT(value) || value === undefined |
t.nullable(T) | T | null | isT(value) || value === null |
t.any | any | true |