Runtime library to validate data against TypeScript interfaces.
This package is the runtime support for validators created by ts-interface-builder. It allows validating data, such as parsed JSON objects received over the network, or parsed JSON or YAML files, to check if they satisfy a TypeScript interface, and to produce informative error messages if they do not.
npm install --save-dev ts-interface-buildernpm install --save ts-interface-checker
Suppose you have a TypeScript file defining an interface:
The first step is to generate some code for runtime checks:
`npm bin`/ts-interface-builder foo.ts
It produces a file like this:
Now at runtime, to check if a value satisfies the Square interface:
;;;Square.check; // OKSquare.check; // OKSquare.check; // Fails with "value.size is missing"Square.check; // Fails with "value.color is not a string"
ts-interface-builder is only needed for the build-time step, and
ts-interface-checker is needed at runtime. That's why the recommendation is to npm-install the
--save-dev flag and the latter using
Checking method calls
If you have an interface with methods, you can validate method call arguments and return values:
After generating the runtime code, you can now check calls like:
;;;Greeter.methodArgs"greet".check; // OKGreeter.methodArgs"greet".check; // Fails with "value.name is not a string"Greeter.methodArgs"greet".check; // Fails with "value.name is missing"Greeter.methodResult"greet".check"hello"; // OKGreeter.methodResult"greet".checknull; // Fails with "value is not a string"
If one type refers to a type defined in another file, you need to tell the interface checker about
all type names when you call
createCheckers(). E.g. given
the produced files
shape-ti.ts do not automatically refer to each other, but
expect you to relate them in
;;;; // Pass in all required type suites.Square.check;
You may check that data contains no extra properties. Note that it is not generally recommended as it this prevents backward compatibility: if you add new properties to an interface, then older code with strict checks will not accept them.
Following on the example above:
Square.strictCheck; // Fails with value.bg is extraneousSquare.strictCheck; // Fails with ...value.color is extraneous