Author: Matthew Scharley
Contributors: See contributors on GitHub
Bugs/Support: Github Issues
License: MIT license
This library is an attempt to manage creating type guards in a sensible way, making them composable and reusable.
$ npm i generic-type-guard
The point of this library is to provide a suite of type guard expressions that are themselves both type safe and composable in a type safe way. To that end we define two new types which are just aliases for the built-in type guard type:
PartialTypeGuard is a type guard which given a value of type
T can prove it is
actually the specialised type
TypeGuard is a type guard that can prove any value
to be of type
T; it is a
What do we mean by type safety when we're talking about something that in a lot of ways is inherantly type unsafe? We simply mean that if you change the definition your interface/variable/whatever you are checking then your type guard should no longer successfully compile. Most of the type safety comes from leveraging the compiler, therefore you must define your typeguards in the following way to make them the most effective:
// this fails.;// this works.;// This works around the gotchas explained below but has other issues, especially with complex types.// All guarantees are void if you use this format.;
It is highly recommended to assign an explicit type to the type guards you create to let the compiler ensure that you've caught everything.
TypeScript structural typing
generic-type-guard works with the TypeScript type system. You are guaranteed that the type guards you write are sufficient to prove
that the thing provided to it conforms in one way or another to the type that the type guard checks for. But that doesn't necessarily mean
that all valid values of that type will be allowed. Put another way, you are guaranteed to never get a false positive but you may get false
negatives. In particular, union types can be troublesome.
An example helps illustrate this:
The above example checks for a single value
"foo". This is a FooBar and so the type system does not complain. But if you try to pass
"bar" into this type guard then it will return false.
Perhaps more insidiously:
Again, checking that
foo is a string is sufficient to prove that it is either a string or undefined.
Fix for structural typing issues
If possible, you should reframe the question. Instead of creating a type to guard against, create a guard and export the type: