1.2.1 • Published 1 year ago

type-slim v1.2.1

Weekly downloads
-
License
MIT
Repository
gitlab
Last release
1 year ago

type-slim

A collection of composable type guard functions.

installation

npm install type-slim

or

yarn install type-slim

usage

type-slim is a pure ESM package. You must use import to use it.

type guard example

import {
  assert,
  isNumber,
  isString,
  isArrayOf,
  isObjectOf,
  isNullable,
  isInstance,
} from 'type-slim'

const value: unknown = null

if (isNumber(value)) {
  value // value now is number
}

if (isString(value)) {
  value // value now is number
}

const isPerson = isObjectOf({
  id: isNumber,
  name: isString,
  addr: isNullable(isString),
  birthDate: isInstance(Date),
  contacts: isArrayOf(
    isObjectOf({
      id: isNumber,
      contact: isString,
    })
  ),
})

interface Contact {
  id: number
  contact: string
}

interface Person {
  id: number
  name: string
  addr: string | null
  birthDate: Date
  contacts: Contact[]
}

interface WithAge extends Person {
  age: number
}

if (isPerson(value)) {
  person(value) // value now satisfies Person interface
  withAge(value) // error TS2345
}

function person(person: Person) {}

function withAge(withAge: WithAge) {}

function withAssert(value: unknown) {
  assert(isPerson, 'not a person', value)
  value.id // type safe
}

functions

function isBool(value)
function isNull(value)
function isNumber(value)
function isString(value)
function isUndefined(value)

function isNonNil(value)
function isNullable(value)
function isOptional(value)

function hasProp(prop, value)
function isSet(value)
function isMap(value)
function isArray(value)
function isObject(value)
function isInstance(value)

function isUnionOf([...guard], value)
function hasPropOf(guard, prop, value)
function isSetOf(guard, value)
function isMapOf([guard, guard], value)
function isArrayOf(guard, value)
function isTupleOf(value)
function isRecordOf(value)
function isObjectOf(value)

function assert(guard, error, value)
1.2.0

1 year ago

1.2.1

1 year ago

1.1.0

1 year ago

1.0.8

2 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago