Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
ts-interface-checker
Advanced tools
Runtime library to validate data against TypeScript interfaces
The ts-interface-checker package is used to perform runtime type checking of objects against TypeScript interfaces. It works by using a companion compiler that generates runtime type information, which can then be used to validate objects at runtime, ensuring they conform to the specified TypeScript interfaces.
Type Checking
This feature allows you to check if an object matches a TypeScript interface. The example shows how to import the checkers, load the generated type information, and use the checker to validate an object.
const { createCheckers } = require('ts-interface-checker');
const ti = require('./type-info');
const { UserChecker } = createCheckers(ti);
const user = { name: 'Alice', age: 25 };
UserChecker.check(user);
Custom Error Reporting
This feature allows you to catch and report errors when an object fails to match the interface. The example demonstrates how to use a try-catch block to handle validation errors and output a custom error message.
const { createCheckers } = require('ts-interface-checker');
const ti = require('./type-info');
const { UserChecker } = createCheckers(ti);
try {
const user = { name: 'Alice', age: '25' };
UserChecker.check(user);
} catch (error) {
console.error('Validation failed:', error.message);
}
Partial Checking
This feature enables checking for partial conformance to an interface, useful when only a subset of properties is required. The example shows how to check a partial object against a TypeScript interface.
const { createCheckers } = require('ts-interface-checker');
const ti = require('./type-info');
const { UserChecker } = createCheckers(ti);
const partialUser = { name: 'Bob' };
UserChecker.strictCheck(partialUser, 'Partial<User>');
io-ts is a TypeScript library for runtime type checking. It uses a different approach than ts-interface-checker by defining types using codecs, which can then be used to validate data at runtime. It also supports functional programming patterns and is more focused on type transformations.
class-validator is a validation library that allows using decorators to define validation rules on class properties. It differs from ts-interface-checker in that it works with class instances rather than plain objects and interfaces, and it integrates with class-transformer for object mapping.
prop-types is a runtime type checking library for React props. It is similar to ts-interface-checker in that it validates objects at runtime, but it is specifically designed for React and uses a different syntax and set of validation functions.
ajv is a JSON schema validator that can validate data against JSON schemas. Unlike ts-interface-checker, which relies on TypeScript interfaces, ajv uses the JSON Schema standard for validation, making it more suitable for validating JSON data formats and inter-operable across different programming languages.
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-builder
npm install --save ts-interface-checker
Suppose you have a TypeScript file defining an interface:
// foo.ts
interface Square {
size: number;
color?: string;
}
The first step is to generate some code for runtime checks:
`npm bin`/ts-interface-builder foo.ts
It produces a file like this:
// foo-ti.js
import * as t from "ts-interface-checker";
export const Square = t.iface([], {
"size": "number",
"color": t.opt("string"),
});
...
Now at runtime, to check if a value satisfies the Square interface:
import fooTI from "./foo-ti";
import {createCheckers} from "ts-interface-checker";
const {Square} = createCheckers(fooTI);
Square.check({size: 1}); // OK
Square.check({size: 1, color: "green"}); // OK
Square.check({color: "green"}); // Fails with "value.size is missing"
Square.check({size: 4, color: 5}); // Fails with "value.color is not a string"
Note that 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
former using --save-dev
flag and the latter using --save
.
If you have an interface with methods, you can validate method call arguments and return values:
// greet.ts
interface Greeter {
greet(name: string): string;
}
After generating the runtime code, you can now check calls like:
import greetTI from "./greet-ti";
import {createCheckers} from "ts-interface-checker";
const {Greeter} = createCheckers(greetTI);
Greeter.methodArgs("greet").check(["Bob"]); // OK
Greeter.methodArgs("greet").check([17]); // Fails with "value.name is not a string"
Greeter.methodArgs("greet").check([]); // Fails with "value.name is missing"
Greeter.methodResult("greet").check("hello"); // OK
Greeter.methodResult("greet").check(null); // 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
// color.ts
export type Color = RGB | string;
export type RGB = [number, number, number];
// shape.ts
import {Color} from "./color";
export interface Square {
size: number;
color?: Color;
}
the produced files color-ti.ts
and shape-ti.ts
do not automatically refer to each other, but
expect you to relate them in createCheckers()
call:
import color from "./color-ti";
import shape from "./shape-ti";
import {createCheckers} from "ts-interface-checker";
const {Square} = createCheckers(shape, color); // Pass in all required type suites.
Square.check({size: 1, color: [255,255,255]});
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({size: 1, color: [255,255,255], bg: "blue"}); // Fails with value.bg is extraneous
Square.strictCheck({size: 1, color: [255,255,255,0.5]}); // Fails with ...value.color[3] is extraneous
Standard Checker
objects do the type checking logic, but are unable to make the TypeScript
compiler aware that an object of unknown
type implements a certain interface.
Basic code:
const unk: unknown = {size: 1, color: "green"};
// Type is unknown, so TypeScript will not let you access the members.
console.log(unk.size); // Error: "Object is of type 'unknown'"
With a Checker
available:
import fooTI from "./foo-ti";
import {createCheckers} from "ts-interface-checker";
const {Square} = createCheckers(fooTI);
const unk: unknown = {size: 1, color: "green"};
if (Square.test(unk)) {
// unk does implement Square, but TypeScript is not aware of it.
console.log(unk.size); // Error: "Object is of type 'unknown'"
}
To enable type guard functionality on the existing test
, and strictTest
functions, Checker
objects should be cast to CheckerT<>
using the appropriate type.
Using CheckerT<>
:
import {Square} from "./foo";
import fooTI from "./foo-ti";
import {createCheckers, CheckerT} from "ts-interface-checker";
const {Square} = createCheckers(fooTI) as {Square: CheckerT<Square>};
const unk: unknown = {size: 1, color: "green"};
if (Square.test(unk)) {
// TypeScript is now aware that unk implements Square, and allows member access.
console.log(unk.size);
}
CheckerT<>
will eventually support type assertions using the check
and strictCheck
functions,
however, this feature is not yet fully working in TypeScript.
FAQs
Runtime library to validate data against TypeScript interfaces
The npm package ts-interface-checker receives a total of 7,548,367 weekly downloads. As such, ts-interface-checker popularity was classified as popular.
We found that ts-interface-checker demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.