Last active
February 28, 2020 11:03
-
-
Save robertdempsey/9ca3134df1800f14cdfe19e19da20503 to your computer and use it in GitHub Desktop.
Example of a type guard with a type predicate using an ajv validator to determine if the object matches a schema
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// where you might have something like this and check a single property exists | |
isMyType(toCheck: any): toCheck is MyType { | |
return !!toCheck.propertyOfMyType | |
} | |
/** | |
Now we can have a generic function that takes type, and we can verify | |
that the whole object validates against a schema, rather than just checking | |
a property or two | |
*/ | |
is<T>(toCheck: any): toCheck is T { | |
return !!this.ajvValidator()(toCheck) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment