2.0.1 • Published 1 year ago

flexible-invariant v2.0.1

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

flexible-invariant 💪💥

flexible-invariant is a flexible alternative to tiny-invariant for building type-safe invariant functions!

flexible-invariant when flexing flexibility counts!

Install

npm install flexible-invariant

Usage

The invariant function takes a value and evaluates its truthiness. If the value is truthy, the function acts as a no-op. Otherwise, it throws an Error.

import { invariant } from 'flexible-invariant'

invariant(truthyValue, 'This should not throw!')

invariant(falsyValue)
// Error('Invariant error')

invariant(falsyValue, 'This will throw!')
// Error('This will throw!')

invariant(falsyValue, () => `This throws the callback's return value!`)
// Error(`This throws the callback's return value!`)

Throwing Custom Exceptions

invariantFactory(exceptionProducer)

Use the invariantFactory function to throw a custom exception.

// utils.ts
import { invariantFactory } from 'flexible-invariant'

const exceptionProducer = (exceptionData: { severity: string; message: string }) => {
  return new Error(`${exceptionData.severity}: ${exceptionData.message}`)
}

export const invariant: (
  condition: any,
  exceptionData: Parameters<typeof exceptionProducer>[0],
) => asserts condition = invariantFactory(exceptionProducer)


// module.ts
import { invariant } from './utils'

invariant(falsyValue, { severity: 'WARN', message: 'Exception data message' })
// Error('WARN: Exception data message')

Credits

2.0.1

1 year ago

2.0.0

1 year ago

1.0.4

1 year ago

1.0.3

1 year ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago