Home

Awesome

ts-validate-type

What?

Validate data at runtime using TypeScript types.

const user = validateType<{ name: string }>(data);

Why?

Building apps in TypeScript often requires handling data we don't know the type of at compile time. For example fetching data:

const myData = fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => response.json())
  .then(response => {
    // casting is unsafe!
    return response as {
      userId: number;
      id: number;
      title: string;
      completed: boolean;
    };
  });

With ts-validate-type:

const myData = fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(response => response.json())
  .then(response => {
    // throws error if response and type don't match
    return validateType<{
      userId: number;
      id: number;
      title: string;
      completed: boolean;
    }>(response);
  });

How?

ts-validate-type requires a compile-time plugin to work. Given this example:

validateType<string>(data);

The plugin will add the <string> type parameter as a runtime argument (a stringified object of type TsValidateType), which is then used for validation:

validateType<string>(data, "{ ... }");

Setup

Note: currently only a TypeScript setup using Babel is supported.

  1. Install dependencies
npm install ts-validate-type
npm install --save-dev babel-plugin-ts-validate-type
  1. Add Babel plugin
"plugins": ["babel-plugin-ts-validate-type", ...]

API

validateType

function validateType<T>(value: unknown): T;

Checks the type of the value passed in matches the type argument T. Throws error if the types don't match, otherwise returns the value passed in.

T must be an inline type. Using type variables like <MyData> is not supported.

Examples

import { validateType } from "ts-validate-type";

try {
  const myValue = validateType<string>(value);
} catch (e) {
  // handle incorrect type
}
validateType<{
  version: "1";
  name: string;
  id: string | number;
  tags: string[];
  nested: { value: boolean };
  tuple: [bigint, bigint];
  data: any;
}>(data);