Runtime type checking in pure javascript.

Overview

Install

npm install function-schema

Usage

import { signature } from 'function-schema';

const myFunction = signature(...ParamTypeChecks)(ReturnValueCheck)(functionDefinition);

Examples:

Define your function signature

import { signature, Void } from 'function-schema';

// myFunction(name: string): void
const myFunction = signature(String)(Void)(
  (name) => console.log(`Hello, ${name}`),
)

Invoke your function:

myFunction('Stan'); // "Hello, Stan"

myFunction(300); // TypeCheckError: Parameter 0 must be an instance of string, received number instead

Return value:

import { signature } from 'function-schema';

// myFunction(name: string): string
const myFunction = signature(String)(String)(
  (name) => `Hello, ${name}`,
)

Optional parameters

import { signature, Optional, Int } from 'function-schema';

// myFunction(name: string, age: Optional<int>): string
const myFunction = signature(String, Optional(Int))(String)(
  (name, age) => `I'm ${name}, and I'm ${age !== undefined ? age : 'infinite'} years old`,
);

myFunction('John', 17); // "I'm John, and I'm 17 years old"
myFunction('Duncan'); // "I'm John, and I'm infinite years old"
myFunction('Didact', null); // "I'm Didact, and I'm infinite years old"
myFunction('Zima', undefined); // "I'm Zima, and I'm infinite years old"

myFunction('Josh', 'Foo'); // TypeCheckError: Parameter 1 must be an instance of Optional<int>, received string instead

Instance Of

import { signature, InstanceOf } from 'function-schema';

class MyClass {
  constructor(name){
    this.name = name;
  }
};

// myFunction(param: MyClass): void
const myFunction = signature(InstanceOf(MyClass))()(
  (param) => console.log(param),
);

// This would have the exact same effect since InstanceOf is the default type check.
const myFunction = signature(MyClass)()(
  (param) => console.log(param),
);

myFunction(new MyClass('John')); // MyClass { name: 'John' }

myFunction(); // TypeCheckError: Parameter 0 must be an instance of MyClass, received undefined instead
myFunction({ name: 'John' }); // TypeCheckError: Parameter 0 must be an instance of MyClass, received object instead

Any

import { signature, Any } from 'function-schema';

// myFunction(name: any): void
const myFunction = signature(Any)()(
  (something) => console.log(something),
)

// myFunction Accepts anything!

myFunction(); // undefined
myFunction(null); // null
myFunction(500); // 500
myFunction('Steve'); // 'Steve'
myFunction({ x: 0, y: 0 }); // { x: 0, y: 0 }

One Of

import { signature, OneOf } from 'function-schema';

const myFunction = signature(OneOf(String, Number))()(
  (value) => console.log(value);
);

myFunction('A string!'); // 'A string!'
myFunction(600); // 600

myFunction(); // TypeCheckError: Parameter 0 must be an instance of OneOf<string, number>, received undefined instead
myFunction(null);  // TypeCheckError: Parameter 0 must be an instance of OneOf<string, number>, received object instead
myFunction(undefined);  // TypeCheckError: Parameter 0 must be an instance of OneOf<string, number>, received undefined instead
myFunction({});  // TypeCheckError: Parameter 0 must be an instance of OneOf<string, number>, received object instead
myFunction(() => 'Boom!');  // TypeCheckError: Parameter 0 must be an instance of OneOf<string, number>, received function instead

Struct

import { signature, Struct } from 'function-schema';

// Define your structure:
const MyType = Struct({
  name: String,
  age: Int,
  favoriteGame: Optional(String),
});

// Define your function
const myFunction = signature(MyType)(String)(
  ({ name, age, favoriteGame}) 
    => `This is ${name}, I'm ${age} years old and ${favoriteGame ? `my favorite game is ${favoriteGame}` : 'have no favorite game'}`;
);

myFunction({
  name: 'John',
  age: 17,
  favoriteGame: 'Halo'
}); // "This is John, I'm 17 years old and my favorite game is Halo"

myFunction({
  name: 'Albert',
  age: 98,
}); // "This is Albert, I'm 94 years old and I have no favorite game"

myFunction({ }); 
// TypeCheckError: Parameter 0 must be an instance of {
// name: string,
// age: int,
// favoriteGame: Optional<String>
// }, received object with these errors: 
//  - name: Parameter 0 must be an instance of string, received undefined instead,
//  - age: Parameter 0 must be an instance of int, received undefined instead
//  instead

Promise Of

import { signature, PromiseOf } from 'function-schema';

const myPromiseProducingFunction = signature()(PromiseOf(String))(
  () => new Promise((accept) => accept('Some Text'))
);

// Or

const myAsyncFunction = signature()(PromiseOf(String))(
  async () => {
    const result = await somePromiseFunction();
    return result;
  }
);

Any

import { signature, Any } from 'function-schema';

// myFunction(name: any): void
const myFunction = signature(Any)()(
  (something) => console.log(something),
)

// myFunction Accepts anything!

myFunction(); // undefined
myFunction(null); // null
myFunction(500); // 500
myFunction('Steve'); // 'Steve'
myFunction({ x: 0, y: 0 }); // { x: 0, y: 0 }

Variadic

import { signature, Variadic } from 'function-schema';

const myFunction = signature(Number, Variadic(String))()(
  (numericValue, ...variadicValues) => console.log(numericValue, variadicValues);
);

myFunction(600); // 600, []
myFunction(600, 'String1'); // 600, ['String1']
myFunction(600, 'String1', 'String2'); // 600, ['String1', 'String2']

myFunction(600, null); // TypeCheckError: Parameter 1 must be an instance of ...string[], received null@1 instead
myFunction(600, 'String1', undefined); // TypeCheckError: Parameter 1 must be an instance of ...string[], received undefined@2 instead
myFunction(600, 'String1', 100, 'String2', 300); // TypeCheckError: Parameter 1 must be an instance of ...string[], received number@2, number@4 instead

Warning For the sake of clarity, only use Variadic as last parameter, it can technically be used in the middle, but that'd be confusing and, at certain circumstances, cause unpredictable behaviors.

ArrayOf

import { signature, ArrayOf } from 'function-schema';

const myFunction = signature(ArrayOf(String))()(
  (arrayOfStrings) => console.log(arrayOfStrings);
);

myFunction([]); // []
myFunction(['String1']); // ['String1']
myFunction(['String1', 'String2']); // ['String1', 'String2']

myFunction(null); // TypeCheckError: Parameter 0 must be an instance of string[], received null instead
myFunction(['String1', undefined]); // TypeCheckError: Parameter 0 must be an instance of string[], received [..., undefined@1] instead
myFunction(['String1', 100, 'String2', 300]); // TypeCheckError: Parameter 0 must be an instance of string[], received [..., number@1, ...] instead

Note: Since arrays could potentially be big, this check will stop at the first invalid entry, all subsequent elements will be ignored.

Tuple

import { signature, Tuple } from 'function-schema';

const myFunction = signature(Tuple(String, Number))()(
  (tuple) => console.log(tuple);
);

myFunction(['String1', 100]); // ['String1', 'String2']
myFunction(['String1', 100, 'Ignored Value']); // ['String1', 100, 'Ignored Value']

myFunction(null); // TypeCheckError: Parameter 0 must be an instance of (string, number), received null instead
myFunction(['String1', undefined]); // TypeCheckError: Parameter 0 must be an instance of (string, number), received (string, undefined) instead
myFunction(['String1', 'String2', 300]); // TypeCheckError: Parameter 0 must be an instance of (string, number), received (string, string) instead

Use signatures as function factories

import { signature } from 'function-schema';

const RequestHandler = signature(MyRequestClass)(MyResponseClass);

const listUsers = RequestHandler((request) => new MyResponseClass());
const createUser = RequestHandler((request) => new MyResponseClass());

Define custom type checks

// A simple type check
const Email = new TypeCheck('email', (entry) => is.email(entry.value));

// A type check with parameters
const NumberRange = (lowerRange, upperRange) => new TypeCheck(`number(from ${lowerRange} to ${upperRange})`, ({value}) => {
  return is.number(value) && value >= lowerRange && value <= upperRange;
});

Generics (sort of)

const MapDelegate = (T, R) => signature(T)(R);

const numbersToString = MapDelegate(Number, String)((n) => n.toString());

[1, 2, 3, 4].map(numbersToString); // ['1', '2', '3', '4'];

[1, '!', 3, 4].map(numbersToString); // TypeCheckError: Parameter 0 must be an instance of number, received string instead.

All type checks so far

Type Check Description Usage
Primitive types
String Check if the given value is a string. (Uses typeof value === 'string') const myFunction = signature(String)(String)
Number Checks if the given value is a number. Numeric strings wont pass const myFunction = signature(Number)(Number)
Boolean Checks if the given value is a boolean. Boolean strings wont pass const myFunction = signature(Boolean)(Boolean)
Any Accepts any value const myFunction = signature(Any)(Any)
Int Accept int numbers only const myFunction = signature(Int)(Int)
Void Alias for Any, useful to give clarity on return types when no value is expected const myFunction = signature()(Void)
Truthy Checks if the given value has any non-falsy value const myFunction = signature(Truthy)(Truthy)
Falsy Checks if the given value has a falsy value const myFunction = signature(Falsy)(Falsy)
Implicit checks
Equality Check If what you provide is a value (not a type or type check), the parameter/return value will be compared to the given value const myFunction = signature('Param 0 will be compared to this string')('Return value will be compared to this string')
Type-Of Check If what you provide is a type (function/class) that doesn't match with the above criteria, the value will be checked with value instanceof Type const myFunction = signature(MyCustomType)(SomeOtherCustomType)
Compound Checks
Optional<Type> Checks if the value is either of the given type, null or undefined const myFunction = signature(Optional(String))(Optional(Number))
OneOf<Type1, Type2, ...> Checks if the value is of one of the given types const myFunction = signature(OneOf(String, Number))(OneOf(Number, Boolean))
Or as an enum:
const myFunction = signature(OneOf('a', 'b'))(OneOf(0, 1))
PromiseOf<Type> Ensures the value is a promise, and once resolved, it checks the promise has returned the correct type const myFunction = signature()(PromiseOf(String))
Struct Checks if the value complies with the given structure. The object must at least have the same properties and each property should validate against its type, extra properties will be ignored. const myFunction = signature(Struct({ name: String, age: Int, status: OneOf('active', 'suspended') }))(Void)
String Checks
Matches(regex) Checks if the value matches the given regular expression const myFunction = signature(Matches(/[a-z]/i))(Matches(/[0-9]/))
Email Checks if the value is a string representing a valid email const myFunction = signature(Email)(Email)
Url Checks if the value is a string representing a valid Url const myFunction = signature(Url)(Url)
NumericString Checks if the value is a string representing a number const myFunction = signature(NumericString)(NumericString)
IntString Checks if the value is a string representing an integer const myFunction = signature(IntString)(IntString)
BooleanString Checks if the value is a string representing a boolean, accepts true or false case-insensitive const myFunction = signature(BooleanString)(BooleanString)
Collection Checks
Variadic<Type> Receives all remaining parameters in a function and check those all are of the given type const myFunction = (Variadic(String))() Or const myFunction = (Int, Variadic(String))()
ArrayOf<Type> Checks that all elements in an array are of the given type const myFunction = (ArrayOf(String))(ArrayOf(String))
Tuple<Type1, Type2, ...> Checks if the value is an array complies with the given structure. const myFunction = (Tuple(String, Int))(Tuple(String, Int, Boolean))

Thanks to:

  • @arasatasaygin - For the is.js library from which I'm actively stealing checks for this library.

TODO

Type Constraints?

(This one looks tricky, might not be a good idea)

Constrained(TypeCheck, Constraint1, Constraint2)
// Or...
TypeCheck.where(Constraint1, Constraint2);
  • Min
  • Max
  • Range
  • MinLength
  • MaxLength
  • RangeLength
  • (value) => boolean
Done as of v0.1.0

Get rid of is.js dependency.

Future Checks:

  • Truthy
  • Falsy

String Checks

  • Matches
  • Email
  • Url
  • NumericString
  • IntString
  • BooleanString: Case insensitive version of OneOf('true', 'false')

Collection Checks

  • Variadic
  • ArrayOf
  • Tuple: Understanding tuple as [TypeCheck1, TypeCheck2, ...]
You might also like...

Snipes Test Flight apps. Configurable & has the ability to use a burner account for checking the status to avoid bans.

Snipes Test Flight apps. Configurable & has the ability to use a burner account for checking the status to avoid bans.

TestFlight Sniper Snipes TestFlight beta apps. Configurable & has the ability to use a burner account for checking the status to avoid bans. Features

Dec 20, 2022

Combine type and value imports using Typescript 4.5 type modifier syntax

type-import-codemod Combines your type and value imports together into a single statement, using Typescript 4.5's type modifier syntax. Before: import

Sep 29, 2022

🧬 A type builder for pagination with prisma and type-graphql.

🧬 Prisma TypeGraphql Pagination Prisma TypeGraphql Pagination builds prisma pagination types for type-graphql. import { ... } from 'type-graphql'

Apr 21, 2022

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Dec 20, 2022

A type programming language which compiles to and interops with type-level TypeScript

Prakaar Prakaar (hindi for "type") is a type programming language which compiles to and interops with type-level TypeScript. Prakaar itself is also a

Sep 21, 2022

A transpiler from golang's type to typescript's type for collaboration between frontend & backend.

A transpiler from golang's type to typescript's type for collaboration between frontend & backend.

go2type go2type.vercel.app (backup site) A typescript transpiler that convert golang's type to typescript's type. Help front-end developer to work fas

Sep 26, 2022

100% type-safe query builder for node-postgres :: Generated types, call any function, tree-shakable, implicit type casts, and more

⚠️ This library is currently in alpha. Contributors wanted! tusken Postgres client from a galaxy far, far away. your database is the source-of-truth f

Dec 29, 2022

Cross-runtime JavaScript framework

Primate, a cross-runtime framework Primate is a full-stack cross-runtime Javascript framework (Node.js and Deno). It relieves you of dealing with repe

Nov 7, 2022

⚗️Nitro provides a powerful toolchain and a runtime framework from the UnJS ecosystem to build and deploy any JavaScript server, anywhere

⚗️Nitro provides a powerful toolchain and a runtime framework from the UnJS ecosystem to build and deploy any JavaScript server, anywhere

Jan 5, 2023
Owner
Jeysson Guevara
Jeysson Guevara
Type predicate functions for checking if a value is of a specific type or asserting that it is.

As-Is Description As-Is contains two modules. Is - Type predicates for checking values are of certain types. As - Asserting values are of a certain ty

Declan Fitzpatrick 8 Feb 10, 2022
A type speed checking website which lets you check your typing speed and shows the real-tme leaderboards with mongodb as DB and express as backend

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Sreehari jayaraj 8 Mar 27, 2022
A library to create pipelines with contexts and strong type checking.

TypePipe A library to create pipelines with contexts and strong type checking. Installation With Node.js and npm installed in your computer run: npm i

Alvaro Fresquet 16 Jun 11, 2022
TypeScript type definitions for Bun's JavaScript runtime APIs

Bun TypeScript type definitions These are the type definitions for Bun's JavaScript runtime APIs. Installation Install the bun-types npm package: # ya

Oven 73 Dec 16, 2022
Zero runtime type-safe CSS in the same file as components

macaron comptime-css is now called macaron! macaron is a zero-runtime and type-safe CSS-in-JS library made with performance in mind Powered by vanilla

Mokshit Jain 205 Jan 4, 2023
🔥 A Powerful JavaScript Module for Generating and Checking Discord Nitro 🌹

DANG: Dreamy's Awesome Nitro Generator Join Our Discord Getting Started Before, We start please follow these Steps: Required* ⭐ Give a Star to this dr

Dreamy Developer 73 Jan 5, 2023
Babel-plugin-amd-checker - Module format checking plugin for Babel usable in both Node.js the web browser environments.

babel-plugin-amd-checker A Babel plugin to check the format of your modules when compiling your code using Babel. This plugin allows you to abort the

Ferdinand Prantl 1 Jan 6, 2022
ToDo list app is a simple web app that helps you organize your day, by adding, checking and deleting daily tasks

TODO List App "To-do list" is a WebApp tool that helps to organize your day. It simply lists the tasks that you need to do and allows you to mark them

Adel Guitoun 8 Oct 18, 2022
This package is for developers to be able to easily integrate bad word checking into their projects.\r This package can return bad words in array or regular expression (regex) form.

Vietnamese Bad Words This package is for developers to be able to easily integrate bad word checking into their projects. This package can return bad

Nguyễn Quang Sáng 8 Nov 3, 2022
The ultimate parity checking as-a-service platform.

Astro Starter Kit: Minimal npm create astro@latest -- --template minimal ??‍?? Seasoned astronaut? Delete this file. Have fun! ?? Project Structure I

Ben Holmes 6 Nov 28, 2022