Using TypeScript
Superstruct is built with TypeScript, and is designed to integrate seamlessly with its guards and assertions. Which means that if you're using TypeScript too you'll get compile-time typings for your data.
🤖 Warning: You must enable TypeScript's
strictNullChecks
option in yourtsconfig.json
for Superstruct to work properly with "optional" types. Note thatstrictNullChecks
is disabled by default. If you enablestrict
,strictNullChecks
will automatically be enabled.
Narrowing Types
Whenever you use the is
or assert
helpers in Superstruct, TypeScript will infer information about your data and give you type safety. For example:
Inside that if
block you can safely access the User
properties id
, name
and email
because TypeScript knows that the data already passed validation.
The same for goes assertions:
This makes it a lot easier to deal with inputs because you don't need to manually guard and refine their types.
Describing Types
You can ensure that you're properly describing your existing TypeScript types with Superstruct by using the Describe
utility. For example:
In this case, the incorrectly defined id
property will cause TypeScript's compilation checks to throw an error. This way your compile-time and run-time validations are never out of sync.
Inferring Types
You can also do the reverse and infer a TypeScript type using an existing Superstruct struct with the Infer
utility. For example:
The User
type above is the same as if you'd defined it by hand:
This saves you from having to duplicate definitions.
🤖 Notice that in each of the cases above, the
User
type and theUser
struct have the same name! This is handy for importing them elsewhere in the codebase at the same time.
Last updated