typesafe-guard
TypeScript icon, indicating that this package has built-in type declarations

0.2.3 • Public • Published

typesafe-guard

ℹ️ The package is ESM-only.

An utility for creating type-safe user-defined type guard for TypeScript.

Motivation

Writing predicate functions is not type-safe because TS trusts the implementation completely even it is invalid:

const isObject = (x: unknown): x is object => true // always true!
const a: string | object = 'some string'
if (isObject(a)) {
	// now TS treats `a` as an object, even actually it is not
}

So I made a more safe way to writing predicate functions, by requiring narrowing the value to the goal type!

Usage

✅ Compiles successfully

interface A {
	a: string
	b: number
}
const isA = predicateFor<A>()((x, ok) => {
	if (!isObjectWithProps({
		a: isString,
		b: isNumber,
	})(x)) return

	return ok(x)
})


❌ Error (which is intended)

interface A {
	a: string
	b: number
}
const isA = predicateFor<A>()((x, ok) => {
	if (!isObject(x)) return

	return ok(x) // error, because x is not narrowed enough
})
interface A {
	a: string
	b: number
}
const isA = predicateFor<A>()((x, ok) => {
	if (!isObject(x)) return

	// error, because the function does not return `ok(...)`
})


ℹ️ You can also create assertion functions from predicate functions!

const assertString: Asserter<string> = asserter(isString)
//                  ^^^^^^^^^^^^^^^^
//                  you need to specify the type yet because
//                  TS requires an explicit type annotation
//                  on assertion functions

Package Sidebar

Install

npm i typesafe-guard

Weekly Downloads

1

Version

0.2.3

License

none

Unpacked Size

21.3 kB

Total Files

10

Last publish

Collaborators

  • andjsrk