Core
assert
assertassert<T>(value: unknown, struct: Struct<T>, message?: string) => asserts value is T
assert(value,User,'The user is invalid!')Assert thatvalue is valid according to astruct. If the value is invalid aStructError will be thrown (the optionalmessage parameter allows you to override error's message).
🤖 When using TypeScript
assertacts as anassertion function, so you can ensure that after calling it the type of thevaluematches the shape of the struct.
create
createcreate<T>(value: unknown, struct: Struct<T>, message?: string) => T
constuser=create(value,User,'Unable to create a user!')Create avalue using the coercion logic that is built-in to the struct, returning the newly coerced value. If the value is invalid aStructError will be thrown (the optionalmessage parameter allows you to override error's message).
🤖 If you want coercion logic like defaulted values, youmust call this helper before running validation.
is
isis<T>(value: unknown, struct: Struct<T>) => value is T
if (is(value,User)){ // ...}Test thatvalue is valid, returning a boolean representing whether it is valid or not.
🤖 When using TypeScript
isacts as a type guard, so you can use it in anifstatement to ensure that inside the statement thevaluematches the shape of the struct.
mask
maskmask<T>(value: unknown, struct: Struct<T>, message?: string) => T
Mask avalue, returning a new value containing only properties defined by astruct. Conceptually this is similar tocreate, except that extra properties are omitted from the newly created value instead of throwing aStructError. If an error is thrown anyway, the optionalmessage parameter allows you to override its message.
Note that whenmask is used withtype — given thattype signals to the core that an object might have arbitrary additional properties — unknown properties will be retained in the returned value.
🤖 Just like
create,maskincludes coercion logic and works recursively.
validate
validatevalidate<T>(value: unknown, struct: Struct<T>, options: Object) => [StructError, T]
Validatevalue, returning a result tuple. If the value is invalid the first element will be aStructError. Otherwise, the first element will beundefined and the second element will be a value that is guaranteed to match the struct.
You can pass{ coerce: true } as the third argument to enable coercion of the input value. As well as pass{ message: 'Your custom error message' } to override the message of theStructError.
Last updated