xype
Runtime JS type checking and matching
xype
uses the new Symbol.hasInstance
to create a robust solution for type-based code,
in the land of JavaScript.
Install
npm install --save xype
Usage
Basic type-checking
;;/*primitives = { number(1, 2.3, NaN, ...), int(1, 2), float(1, 1.3), string('hello'), bool(true, false), nil(null, undefined), fn(function foo() {})}isinstance = basically, instanceof as a function*/ ; // true
Optional
xype
introduces a new optional<T>
type, which functions much like haskell's Maybe<T>
.
;const maybeNumber = ;; // true; // true; // false
Union
xype
uses, and exposes, the Union<...Ts>
type, which functions like the type ZipCode = String | Number
declaration.
;const ZipCode = ;; // true; // false; // true
Records
;const Person = ; // Records can be extended infinitelyconst AgelessPerson = Person;const p = name: 'Foo' ;; // true; // truepage = 4;; // true; // falsedelete pname;; // false; // false // Records are recursiveconst Address = ;
Typed Arrays
;;; ; // true; // false; // true - defaults to type `any`
Tuples
;;; const HTTPStatusCode = ;; // true; // false; // false
Compound Reflection
;;;const EnabledUser = ;/*This is equal to:import { record, arrayOf } from 'xype/compound';import { int, string } from 'xype/primitives';import { optional, union, literal } from 'xype/meta';const EnabledUser = record({ username: string, address: record({ city: string, street: string, house: int, zip: optional(union(int, string)), }), enabled: literal(true), comments: arrayOf({ content: string })});*/
Creating new types
;const EmptyArray = ; ; // true; // false // however, for this instance you should probably go for a `tuple()`
Matching
xype
exposes a relatively powerful matching function, aimimng to emulate haskell's pattern-matching capabilities.
The match
function matches a type/primitive and maps it to a function/value.
It uses the above mentioned reflection system for its type
arguments, so objects are turned into record
types,
arrays turn into arrayOf<T>
and numbers/strings/null/booleans become literal<V>
types.
Otherwise, see examples below:
;const isEven = ;t;t;t; const getAge = ; const p = name: 'foo' age: 3 ;t;delete page;t; const factorial = ; t; const EmptyArray = ; const tail = ;t;t; const strictFib = ;t;t; const get = ;const user = username: 'foobar';t;t; // matchTo is used to match expression without creating a functionconst num = 3;const isNumEven = ; // false