TypeScript-is
typescript-is is a TypeScript compiler transformer that generates runtime type-check functions directly from static TypeScript types. It automates the process of creating type predicates for `any` or `unknown` data, which is common when working with external data sources like API responses or user-uploaded files. The library inspects type definitions at compile time and emits JavaScript functions that meticulously validate incoming objects against those definitions. Currently at version 0.20.0, the project is officially deprecated and will not be updated for TypeScript versions 4.8 and above. Users are strongly advised to migrate to `typia` for newer TypeScript environments. Before its deprecation, the project aimed for regular, feature-driven releases. Its core differentiator lies in leveraging the TypeScript compiler API to avoid manual type predicate writing, aiming for comprehensive type-safety at runtime for serializable JavaScript objects.
Common errors
-
Error: No transformer was applied. Did you forget to configure 'ttypescript' or your bundler?
cause The `typescript-is` transformer was not successfully integrated into the build process, or `ttypescript` was not used/configured correctly.fixEnsure `ttypescript` is installed, `tsconfig.json` correctly points to the transformer (`"transform": "typescript-is/lib/transform-inline/transformer"`), and the build command uses `ttsc` instead of `tsc`. -
Validation failed at $: expected 'foo' in object, found: {}cause The runtime data provided to `assertEquals` or `is` did not conform to the expected TypeScript type definition, specifically missing the 'foo' property.fixInspect the input data and the target type definition (e.g., `interface Foo { foo: string; }`) to identify the mismatch. Adjust the data to fit the type or refine the type definition. -
TypeError: Function calls are not supported at runtime by `typescript-is`. Consider using `functionBehavior`.
cause Attempted to validate a TypeScript type that includes a function signature (e.g., `type MyType = { handler: () => void }`) without explicit handling.fixConfigure the `functionBehavior` option in your `tsconfig.json` plugin settings. Options include `ignoreFunctions` (to skip function validation) or `typeof` (to perform a basic `typeof 'function'` check).
Warnings
- breaking `typescript-is` is officially deprecated and will not receive updates or support for TypeScript versions 4.8 and higher. Continuing to use it with newer TypeScript versions may lead to build failures or unexpected behavior.
- gotcha When using bundlers or loaders like `ts-loader` with the `transpileOnly` flag set to `true`, TypeScript transformers are bypassed. This means `typescript-is` will not apply its type transformations, leading to no runtime checks.
- gotcha `typescript-is` relies on a TypeScript compiler transformer, which is not natively supported by `tsc`. It requires `ttypescript` or programmatic configuration of the TypeScript API to inject the transformer into your build process.
- gotcha The library is designed to generate type predicates for *serializable* JavaScript objects. It will not work for types that involve non-serializable constructs like functions, classes (unless configured with decorators and `reflect-metadata`), or complex symbols, without specific configuration or limitations.
Install
-
npm install typescript-is -
yarn add typescript-is -
pnpm add typescript-is
Imports
- is
const { is } = require('typescript-is');import { is } from 'typescript-is'; - assertEquals
assertEquals<Type>(value); // Used without ttypescript configured
import { assertEquals } from 'typescript-is'; - Transformer Configuration
{ "transform": "typescript-is/transformer" }{ "transform": "typescript-is/lib/transform-inline/transformer" }
Quickstart
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"plugins": [
{ "transform": "typescript-is/lib/transform-inline/transformer" }
]
},
"include": ["src/**/*.ts"]
}
// package.json (excerpt)
// ...
// "scripts": {
// "build": "ttsc",
// "start": "node dist/index.js"
// }
// ...
// src/index.ts
import { assertEquals } from 'typescript-is';
interface User {
id: number;
name: string;
email?: string;
}
function processUserData(data: unknown) {
try {
// This call is transformed by typescript-is to perform runtime checks
assertEquals<User>(data);
console.log("User data is valid:", data);
// At this point, 'data' is safely typed as User
console.log(`Processing user ${data.name} (ID: ${data.id})`);
} catch (error: any) {
console.error("Invalid user data:", error.message);
}
}
// Example valid data
processUserData({ id: 1, name: "Alice", email: "alice@example.com" });
processUserData({ id: 2, name: "Bob" });
// Example invalid data
processUserData({ id: "3", name: "Charlie" }); // ID is string, expected number
processUserData({ id: 4 }); // Missing name
processUserData({ id: 5, name: "David", age: 30 }); // Extra property (strict)