Verify-TS
This package provides a decorator to help with verifying input to methods.
Install
npm i ts-verify
TypeScript Usage
To use in typescript, import the functions.
;
To verify parameters of a method, use like this:
public testOneNumber@isv > 0 value: number: number
In this example, the value parameter will throw an exception if a number is pased that is not greater than 0.
We can use any function that returns a boolean value:
public testArraySumGteTen @isa.reducep + c >= 10 array: number
This will throw if the passed array of numbers does not sum to at least 10.
Type Checking
You can also ensure types are correct:
Without the additional "number"
parameter, the following would be valid:
pay"4";
However, with this additional checking, the above will throw.
Alternatively, you can just check for a type:
Contextual Checking
Validation functions can access the object the method is being called on:
The optional second parameter to an @is
call will pass a reference to the
object. We can therefore access methods and fields on this object. For
typechecking, either the function or parameter must have a type
parameter/annotation, i.e.:
or
Full Method Checking
A validation function can be called inside the @validate()
call as well. This
function has access to all arguments in the method, for example:
The order of the arguments in the validation function is the same order as
passed in the method. In this example, a
would be min
, and b
would be
max
.
The validation function inside @validate()
can also access the object context.
Note the name of the argument inside the object passed to @validate()
:
The first parameter to contextFn
is the object. The remaining are the method
arguments. This can be contrasted to argFn
which just passes the arguments.
For a more complete example: