Skip to content

Instantly share code, notes, and snippets.

@robertdempsey
Last active February 28, 2020 11:03
Show Gist options
  • Save robertdempsey/9ca3134df1800f14cdfe19e19da20503 to your computer and use it in GitHub Desktop.
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
// 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