Skip to content

andjsrk/typesafe-guard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 derive an assertion function from a predicate function:

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

ℹ️ You can write a validator, which is a predicate with fail reason:

const validateString = validatorFor<string>()((x, ok, fail) => {
	if (!isString(x)) return fail('Not a string.')
	
	return ok(x)
})

// you can derive a predicate function from a validator
const myIsString = predicateFromValidator(validateString)

// you can derive an asserter from a validator
const assertString: Asserter<string> = asserterFromValidator(validateString)