Predicates

Overview

Predicates are boolean functions that return true or false for a given input. Predicates are useful for those moments where we want to assert if an object's type tag is of an specific type. Hence why the TypeTags object has a predicate for each of its types.

import { TypeTags } from 'typetags'
TypeTags.String
// → [object String]
TypeTags.isString('🎉')
// → true
TypeTags.Array
// → [object Array]
TypeTags.isArray(TypeTags.Array)
// → true

There are two kinds of predicate functions to help us with assertions: generics and specifics.

Generics

Used for overall checks. For example, to check if an object has a default type tag:

const { TypeTags } = require('typetags')
const o = Object.create(null)
TypeTags.isDefault(o)
// → false

Specifics

Allows us to check for specific tags or groups of tags:

const { TypeTags } = require('typetags')
const maybeTyped = [1, 2, 3]
TypeTags.isTypedArray(maybeTyped)
// → false
TypeTags.get(arr)
// → '[object Array]'

We can take advantage of object destructuring to extract predicates from the TypeTags object.

import { TypeTags } from 'typetags'
const { isArray, isSet } = TypeTags
console.log(isArray([]))
// → true
console.log(isSet(''))
// → false

We can also destructure on import when using require with common-js. There's no need to instantiate it as TypeTags itself is not a function or a constructor.

const { isMap } = require('typetags').TypeTags
const cool = new Map()
console.log(isMap(cool))
// → true

Signature

declare type PredicateNames = `is${Types | NestedPredicates}`
declare interface Predicate {
predicate(value: any): boolean
}
declare type PredicateMapper<Type> = {
[Prop in keyof Type as PredicateNames]: Type[Prop]
}
declare type Predicates = PredicateMapper<Predicate>