TypeScript-is

0.20.0 · deprecated · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure `typescript-is` with `ttypescript` in `tsconfig.json` and use `assertEquals` to perform runtime type validation on an `unknown` input, ensuring type safety for `User` objects. It shows both valid and invalid data scenarios.

{
  "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)

view raw JSON →