Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-runtime-typecheck

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-runtime-typecheck - npm Package Compare versions

Comparing version 1.2.0 to 2.0.0

cjs/type-cast/as-instance.d.ts

6

cjs/index.d.ts
export * from './type-cast/as-json';
export * from './type-cast/as-primitive';
export * from './type-cast/as-struct';
export * from './type-cast/as-union';
export * from './type-cast/as-recursive';
export * from './type-check/is-json';
export * from './type-check/is-primitive';
export * from './type-check/is-struct';
export * from './type-check/is-union';
export * from './type-check/is-recursive';
export * from './type-coerce/make-primative';

@@ -15,2 +19,2 @@ export { Index, Indexable } from './Index.type';

export { InterfacePattern } from './InterfacePattern.type';
export { TypeAssert } from './TypeAssert.type';
export { TypeCheck } from './TypeCheck.type';

28

cjs/index.js

@@ -11,2 +11,6 @@ 'use strict';

var asStruct = require('./type-cast/as-struct.js');
var isUnion = require('./type-check/is-union.js');
var asUnion = require('./type-cast/as-union.js');
var isRecursive = require('./type-check/is-recursive.js');
var asRecursive = require('./type-cast/as-recursive.js');
var makePrimative = require('./type-coerce/make-primative.js');

@@ -19,2 +23,3 @@

exports.isDefined = isPrimitive.isDefined;
exports.isDictionary = isPrimitive.isDictionary;
exports.isFunction = isPrimitive.isFunction;

@@ -27,2 +32,3 @@ exports.isIndex = isPrimitive.isIndex;

exports.isOptBoolean = isPrimitive.isOptBoolean;
exports.isOptDictionary = isPrimitive.isOptDictionary;
exports.isOptFunction = isPrimitive.isOptFunction;

@@ -32,5 +38,3 @@ exports.isOptIndex = isPrimitive.isOptIndex;

exports.isOptNumber = isPrimitive.isOptNumber;
exports.isOptRecord = isPrimitive.isOptRecord;
exports.isOptString = isPrimitive.isOptString;
exports.isRecord = isPrimitive.isRecord;
exports.isString = isPrimitive.isString;

@@ -51,5 +55,5 @@ exports.isUndefined = isPrimitive.isUndefined;

exports.asArray = asPrimitive.asArray;
exports.asArrayRecursive = asPrimitive.asArrayRecursive;
exports.asBoolean = asPrimitive.asBoolean;
exports.asDefined = asPrimitive.asDefined;
exports.asDictionary = asPrimitive.asDictionary;
exports.asFunction = asPrimitive.asFunction;

@@ -60,4 +64,4 @@ exports.asIndex = asPrimitive.asIndex;

exports.asOptArray = asPrimitive.asOptArray;
exports.asOptArrayRecursive = asPrimitive.asOptArrayRecursive;
exports.asOptBoolean = asPrimitive.asOptBoolean;
exports.asOptDictionary = asPrimitive.asOptDictionary;
exports.asOptFunction = asPrimitive.asOptFunction;

@@ -67,7 +71,3 @@ exports.asOptIndex = asPrimitive.asOptIndex;

exports.asOptNumber = asPrimitive.asOptNumber;
exports.asOptRecord = asPrimitive.asOptRecord;
exports.asOptRecordRecursive = asPrimitive.asOptRecordRecursive;
exports.asOptString = asPrimitive.asOptString;
exports.asRecord = asPrimitive.asRecord;
exports.asRecordRecursive = asPrimitive.asRecordRecursive;
exports.asString = asPrimitive.asString;

@@ -78,4 +78,16 @@ exports.isOptStruct = isStruct.isOptStruct;

exports.asStruct = asStruct.asStruct;
exports.isOptUnion = isUnion.isOptUnion;
exports.isUnion = isUnion.isUnion;
exports.asOptUnion = asUnion.asOptUnion;
exports.asUnion = asUnion.asUnion;
exports.isArrayOf = isRecursive.isArrayOf;
exports.isDictionaryOf = isRecursive.isDictionaryOf;
exports.isOptArrayOf = isRecursive.isOptArrayOf;
exports.isOptDictionaryOf = isRecursive.isOptDictionaryOf;
exports.asArrayOf = asRecursive.asArrayOf;
exports.asDictionaryOf = asRecursive.asDictionaryOf;
exports.asOptArrayOf = asRecursive.asOptArrayOf;
exports.asOptDictionaryOf = asRecursive.asOptDictionaryOf;
exports.makeBoolean = makePrimative.makeBoolean;
exports.makeNumber = makePrimative.makeNumber;
exports.makeString = makePrimative.makeString;
import type { Dictionary } from './Dictionary.type';
import type { TypeAssert, UnwrapTypeAssert } from './TypeAssert.type';
export declare type InterfacePattern = Dictionary<TypeAssert<unknown>>;
import type { TypeCheck, UnwrapTypeCheck } from './TypeCheck.type';
export declare type InterfacePattern = Dictionary<TypeCheck<unknown>>;
export declare type UnwrapInterfacePattern<Pattern extends InterfacePattern> = {
[K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>;
[K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>;
};

@@ -1,3 +0,1 @@

import type { Dictionary } from './Dictionary.type';
import type { UnknownFunction } from './UnknownFunction.type';
export declare function memoize<P extends (UnknownFunction | Dictionary), R>(fn: (par: P) => R): (par: P) => R;
export declare function memoize<P extends object, R>(fn: (par: P) => R): (par: P) => R;

@@ -6,5 +6,5 @@ 'use strict';

function memoize(fn) {
const map = new WeakMap();
return (par) => {
let result = map.get(par);
var map = new WeakMap();
return function (par) {
var result = map.get(par);
if (!result) {

@@ -11,0 +11,0 @@ result = fn(par);

import type { JSONValue, JSONArray, JSONObject } from '../JSONValue.type';
import { OptionalTypeCast, TypeCast } from '../TypeCast.type';
import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
export declare const asJSONValue: (obj: unknown, fallback?: import("..").Optional<string | number | boolean | JSONObject | JSONArray>) => JSONValue;

@@ -4,0 +4,0 @@ export declare const asJSONArray: TypeCast<JSONArray, JSONValue>;

@@ -8,10 +8,10 @@ 'use strict';

const asJSONValue = typeCast.typeCast(isJson.isJSONValue);
const __isJSONArray = isJson.isJSONArray;
const __isJSONObject = isJson.isJSONObject;
const asJSONArray = typeCast.typeCast(__isJSONArray);
const asJSONObject = typeCast.typeCast(__isJSONObject);
const asOptJSONValue = typeCast.optTypeCast(isJson.isJSONValue);
const asOptJSONArray = typeCast.optTypeCast(__isJSONArray);
const asOptJSONObject = typeCast.optTypeCast(__isJSONObject);
var asJSONValue = typeCast.typeCast(isJson.isJSONValue);
var __isJSONArray = isJson.isJSONArray;
var __isJSONObject = isJson.isJSONObject;
var asJSONArray = typeCast.typeCast(__isJSONArray);
var asJSONObject = typeCast.typeCast(__isJSONObject);
var asOptJSONValue = typeCast.optTypeCast(isJson.isJSONValue);
var asOptJSONArray = typeCast.optTypeCast(__isJSONArray);
var asOptJSONObject = typeCast.optTypeCast(__isJSONObject);

@@ -18,0 +18,0 @@ exports.asJSONArray = asJSONArray;

@@ -1,2 +0,1 @@

import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
import type { Optional } from '../Optional.type';

@@ -9,16 +8,12 @@ export declare const asString: (obj: unknown, fallback?: string | undefined) => string;

export declare const asArray: (obj: unknown, fallback?: unknown[] | undefined) => unknown[];
export declare const asRecord: (obj: unknown, fallback?: Record<string, unknown> | undefined) => Record<string, unknown>;
export declare const asDictionary: (obj: unknown, fallback?: Record<string, unknown> | undefined) => Record<string, unknown>;
export declare const asFunction: (obj: unknown, fallback?: import("..").UnknownFunction<unknown> | undefined) => import("..").UnknownFunction<unknown>;
export declare function asDefined<T>(obj: Optional<T>, fallback?: NonNullable<T>): NonNullable<T>;
export declare const asOptString: OptionalTypeCast<string, unknown>;
export declare const asOptNumber: OptionalTypeCast<number, unknown>;
export declare const asOptIndex: OptionalTypeCast<import("..").Index, unknown>;
export declare const asOptIndexable: OptionalTypeCast<Record<import("..").Index, unknown>, unknown>;
export declare const asOptBoolean: OptionalTypeCast<boolean, unknown>;
export declare const asOptArray: OptionalTypeCast<unknown[], unknown>;
export declare const asOptRecord: OptionalTypeCast<Record<string, unknown>, unknown>;
export declare const asOptFunction: OptionalTypeCast<import("..").UnknownFunction<unknown>, unknown>;
export declare const asArrayRecursive: <T>(par: (obj: unknown) => T) => TypeCast<T[], unknown>;
export declare const asRecordRecursive: <T>(par: (obj: unknown) => T) => TypeCast<Record<string, T>, unknown>;
export declare const asOptArrayRecursive: <T>(par: (obj: unknown) => T) => OptionalTypeCast<T[], unknown>;
export declare const asOptRecordRecursive: <T>(par: (obj: unknown) => T) => OptionalTypeCast<Record<string, T>, unknown>;
export declare const asOptString: import("../TypeCast.type").OptionalTypeCast<string, unknown>;
export declare const asOptNumber: import("../TypeCast.type").OptionalTypeCast<number, unknown>;
export declare const asOptIndex: import("../TypeCast.type").OptionalTypeCast<import("..").Index, unknown>;
export declare const asOptIndexable: import("../TypeCast.type").OptionalTypeCast<Record<import("..").Index, unknown>, unknown>;
export declare const asOptBoolean: import("../TypeCast.type").OptionalTypeCast<boolean, unknown>;
export declare const asOptArray: import("../TypeCast.type").OptionalTypeCast<unknown[], unknown>;
export declare const asOptDictionary: import("../TypeCast.type").OptionalTypeCast<Record<string, unknown>, unknown>;
export declare const asOptFunction: import("../TypeCast.type").OptionalTypeCast<import("..").UnknownFunction<unknown>, unknown>;

@@ -7,12 +7,11 @@ 'use strict';

var typeCast = require('./type-cast.js');
var memoize = require('../memoize.js');
const asString = typeCast.typeCast(isPrimitive.isString);
const asNumber = typeCast.typeCast(isPrimitive.isNumber);
const asIndex = typeCast.typeCast(isPrimitive.isIndex);
const asIndexable = typeCast.typeCast(isPrimitive.isIndexable);
const asBoolean = typeCast.typeCast(isPrimitive.isBoolean);
const asArray = typeCast.typeCast(isPrimitive.isArray);
const asRecord = typeCast.typeCast(isPrimitive.isRecord);
const asFunction = typeCast.typeCast(isPrimitive.isFunction);
var asString = typeCast.typeCast(isPrimitive.isString);
var asNumber = typeCast.typeCast(isPrimitive.isNumber);
var asIndex = typeCast.typeCast(isPrimitive.isIndex);
var asIndexable = typeCast.typeCast(isPrimitive.isIndexable);
var asBoolean = typeCast.typeCast(isPrimitive.isBoolean);
var asArray = typeCast.typeCast(isPrimitive.isArray);
var asDictionary = typeCast.typeCast(isPrimitive.isDictionary);
var asFunction = typeCast.typeCast(isPrimitive.isFunction);
function asDefined(obj, fallback) {

@@ -25,56 +24,17 @@ if (isPrimitive.isDefined(obj)) {

}
throw new Error(`Unable to cast ${typeof obj} to NonNullable<unknown>`);
throw new Error("Unable to cast " + typeof obj + " to NonNullable<unknown>");
}
const asOptString = typeCast.optTypeCast(isPrimitive.isString);
const asOptNumber = typeCast.optTypeCast(isPrimitive.isNumber);
const asOptIndex = typeCast.optTypeCast(isPrimitive.isIndex);
const asOptIndexable = typeCast.optTypeCast(isPrimitive.isIndexable);
const asOptBoolean = typeCast.optTypeCast(isPrimitive.isBoolean);
const asOptArray = typeCast.optTypeCast(isPrimitive.isArray);
const asOptRecord = typeCast.optTypeCast(isPrimitive.isRecord);
const asOptFunction = typeCast.optTypeCast(isPrimitive.isFunction);
const asArrayRecursive = memoize.memoize((visitor) => {
return (obj, fallback) => {
if (isPrimitive.isNullish(obj) && typeof fallback !== 'undefined') {
return fallback;
}
return asArray(obj, fallback).map((val) => visitor(val));
};
});
const asRecordRecursive = memoize.memoize((visitor) => {
return (obj, fallback) => {
if (isPrimitive.isNullish(obj) && typeof fallback !== 'undefined') {
return fallback;
}
const source = asRecord(obj);
const record = {};
for (const key in source) {
record[key] = visitor(source[key]);
}
return record;
};
});
const asOptArrayRecursive = memoize.memoize((visitor) => {
const convert = asArrayRecursive(visitor);
return (obj) => {
if (isPrimitive.isNullish(obj)) {
return undefined;
}
return convert(obj);
};
});
const asOptRecordRecursive = memoize.memoize((visitor) => {
const convert = asRecordRecursive(visitor);
return (obj) => {
if (isPrimitive.isNullish(obj)) {
return undefined;
}
return convert(obj);
};
});
var asOptString = typeCast.optTypeCast(isPrimitive.isString);
var asOptNumber = typeCast.optTypeCast(isPrimitive.isNumber);
var asOptIndex = typeCast.optTypeCast(isPrimitive.isIndex);
var asOptIndexable = typeCast.optTypeCast(isPrimitive.isIndexable);
var asOptBoolean = typeCast.optTypeCast(isPrimitive.isBoolean);
var asOptArray = typeCast.optTypeCast(isPrimitive.isArray);
var asOptDictionary = typeCast.optTypeCast(isPrimitive.isDictionary);
var asOptFunction = typeCast.optTypeCast(isPrimitive.isFunction);
exports.asArray = asArray;
exports.asArrayRecursive = asArrayRecursive;
exports.asBoolean = asBoolean;
exports.asDefined = asDefined;
exports.asDictionary = asDictionary;
exports.asFunction = asFunction;

@@ -85,4 +45,4 @@ exports.asIndex = asIndex;

exports.asOptArray = asOptArray;
exports.asOptArrayRecursive = asOptArrayRecursive;
exports.asOptBoolean = asOptBoolean;
exports.asOptDictionary = asOptDictionary;
exports.asOptFunction = asOptFunction;

@@ -92,7 +52,3 @@ exports.asOptIndex = asOptIndex;

exports.asOptNumber = asOptNumber;
exports.asOptRecord = asOptRecord;
exports.asOptRecordRecursive = asOptRecordRecursive;
exports.asOptString = asOptString;
exports.asRecord = asRecord;
exports.asRecordRecursive = asRecordRecursive;
exports.asString = asString;

@@ -1,2 +0,2 @@

export declare const asStruct: <Pattern extends Record<string, import("..").TypeAssert<unknown>>>(par: Pattern) => (obj: unknown, fallback?: { [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; } | undefined) => { [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; };
export declare const asOptStruct: <Pattern extends Record<string, import("..").TypeAssert<unknown>>>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; }, unknown>;
export declare const asStruct: <Pattern extends Record<string, import("..").TypeCheck<unknown>>>(par: Pattern) => (obj: unknown, fallback?: { [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; } | undefined) => { [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; };
export declare const asOptStruct: <Pattern extends Record<string, import("..").TypeCheck<unknown>>>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;

@@ -9,6 +9,6 @@ 'use strict';

const asStruct = memoize.memoize((pattern) => {
var asStruct = memoize.memoize(function (pattern) {
return typeCast.typeCast(isStruct.isStruct(pattern));
});
const asOptStruct = memoize.memoize((pattern) => {
var asOptStruct = memoize.memoize(function (pattern) {
return typeCast.optTypeCast(isStruct.isStruct(pattern));

@@ -15,0 +15,0 @@ });

import type { Optional } from '../Optional.type';
import type { TypeAssert } from '../TypeAssert.type';
import type { TypeCheck } from '../TypeCheck.type';
import type { OptionalTypeCast } from '../TypeCast.type';
export declare function optTypeCast<Input, Output>(isType: TypeAssert<Output>): OptionalTypeCast<Output, Optional<Input>>;
export declare function typeCast<Output>(isType: TypeAssert<Output>): (obj: unknown, fallback?: Output) => Output;
export declare function optTypeCast<Input, Output>(isType: TypeCheck<Output>): OptionalTypeCast<Output, Optional<Input>>;
export declare function typeCast<Output>(isType: TypeCheck<Output>): (obj: unknown, fallback?: Output) => Output;

@@ -8,3 +8,3 @@ 'use strict';

function optTypeCast(isType) {
return (obj) => {
return function (obj) {
var _a;

@@ -17,7 +17,7 @@ if (isPrimitive.isNullish(obj)) {

}
throw new Error(`Unable to cast ${typeof obj} to Optional<${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}>`);
throw new Error("Unable to cast " + typeof obj + " to Optional<" + ((_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown') + ">");
};
}
function typeCast(isType) {
return (obj, fallback) => {
return function (obj, fallback) {
var _a;

@@ -30,3 +30,3 @@ if (isType(obj)) {

}
throw new Error(`Unable to cast ${typeof obj} to ${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}`);
throw new Error("Unable to cast " + typeof obj + " to " + ((_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'));
};

@@ -33,0 +33,0 @@ }

@@ -6,8 +6,8 @@ import type { Index, Indexable } from '../Index.type';

import type { UnknownFunction } from '../UnknownFunction.type';
export declare function isRecord(obj: unknown): obj is Dictionary;
export declare namespace isRecord {
export declare function isDictionary(obj: unknown): obj is Dictionary;
export declare namespace isDictionary {
var TYPE_NAME: string;
}
export declare function isOptRecord(obj: unknown): obj is Optional<Dictionary>;
export declare namespace isOptRecord {
export declare function isOptDictionary(obj: unknown): obj is Optional<Dictionary>;
export declare namespace isOptDictionary {
var TYPE_NAME: string;

@@ -14,0 +14,0 @@ }

@@ -5,10 +5,10 @@ 'use strict';

function isRecord(obj) {
function isDictionary(obj) {
return obj !== null && typeof obj === 'object' && Array.isArray(obj) === false;
}
isRecord.TYPE_NAME = 'Dictionary';
function isOptRecord(obj) {
return isRecord(obj) || isNullish(obj);
isDictionary.TYPE_NAME = 'Dictionary';
function isOptDictionary(obj) {
return isDictionary(obj) || isNullish(obj);
}
isOptRecord.TYPE_NAME = 'Optional<Dictionary>';
isOptDictionary.TYPE_NAME = 'Optional<Dictionary>';
function isFunction(obj) {

@@ -86,2 +86,3 @@ return typeof obj === 'function';

exports.isDefined = isDefined;
exports.isDictionary = isDictionary;
exports.isFunction = isFunction;

@@ -94,2 +95,3 @@ exports.isIndex = isIndex;

exports.isOptBoolean = isOptBoolean;
exports.isOptDictionary = isOptDictionary;
exports.isOptFunction = isOptFunction;

@@ -99,6 +101,4 @@ exports.isOptIndex = isOptIndex;

exports.isOptNumber = isOptNumber;
exports.isOptRecord = isOptRecord;
exports.isOptString = isOptString;
exports.isRecord = isRecord;
exports.isString = isString;
exports.isUndefined = isUndefined;

@@ -1,8 +0,8 @@

import type { TypeAssert, UnwrapTypeAssert } from '../TypeAssert.type';
import type { TypeCheck, UnwrapTypeCheck } from '../TypeCheck.type';
import type { Optional } from '../Optional.type';
export declare const isStruct: <Pattern extends Record<string, TypeAssert<unknown>>>(par: Pattern) => TypeAssert<{ [K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>; }> & {
export declare const isStruct: <Pattern extends Record<string, TypeCheck<unknown>>>(par: Pattern) => TypeCheck<{ [K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>; }> & {
TYPE_NAME: string;
};
export declare const isOptStruct: <Pattern extends Record<string, TypeAssert<unknown>>>(par: Pattern) => TypeAssert<Optional<{ [K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>; }>> & {
export declare const isOptStruct: <Pattern extends Record<string, TypeCheck<unknown>>>(par: Pattern) => TypeCheck<Optional<{ [K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>; }>> & {
TYPE_NAME: string;
};

@@ -9,11 +9,15 @@ 'use strict';

function structLabel(pattern) {
const entries = Object.entries(pattern);
return entries.length === 0 ? '{}' : `{ ${entries.map(([name, check]) => check.TYPE_NAME ? `${name}: ${check.TYPE_NAME}` : name).join('; ')} }`;
var entries = Object.entries(pattern);
return entries.length === 0 ? '{}' : "{ " + entries.map(function (_a) {
var name = _a[0], check = _a[1];
return check.TYPE_NAME ? name + ": " + check.TYPE_NAME : name;
}).join('; ') + " }";
}
const isStruct = memoize.memoize((pattern) => {
const fn = (val) => {
if (!isPrimitive.isRecord(val)) {
var isStruct = memoize.memoize(function (pattern) {
var fn = function (val) {
if (!isPrimitive.isDictionary(val)) {
return false;
}
for (const [prop, check] of Object.entries(pattern)) {
for (var _i = 0, _a = Object.entries(pattern); _i < _a.length; _i++) {
var _b = _a[_i], prop = _b[0], check = _b[1];
if (!check(val[prop])) {

@@ -28,11 +32,12 @@ return false;

});
const isOptStruct = memoize.memoize((pattern) => {
const fn = (val) => {
var isOptStruct = memoize.memoize(function (pattern) {
var fn = function (val) {
if (isPrimitive.isNullish(val)) {
return true;
}
if (!isPrimitive.isRecord(val)) {
if (!isPrimitive.isDictionary(val)) {
return false;
}
for (const [prop, check] of Object.entries(pattern)) {
for (var _i = 0, _a = Object.entries(pattern); _i < _a.length; _i++) {
var _b = _a[_i], prop = _b[0], check = _b[1];
if (!check(val[prop])) {

@@ -39,0 +44,0 @@ return false;

@@ -14,3 +14,3 @@ 'use strict';

}
throw new Error(`Unable to cast ${typeof obj} to String`);
throw new Error("Unable to cast " + typeof obj + " to String");
}

@@ -22,3 +22,3 @@ function makeNumber(obj) {

if (isPrimitive.isString(obj)) {
const value = parseFloat(obj);
var value = parseFloat(obj);
if (!isNaN(value)) {

@@ -31,3 +31,3 @@ return value;

}
throw new Error(`Unable to cast ${typeof obj} to Number`);
throw new Error("Unable to cast " + typeof obj + " to Number");
}

@@ -49,3 +49,3 @@ function makeBoolean(obj) {

}
throw new Error(`Unable to cast ${typeof obj} to Boolean`);
throw new Error("Unable to cast " + typeof obj + " to Boolean");
}

@@ -52,0 +52,0 @@

export * from './type-cast/as-json';
export * from './type-cast/as-primitive';
export * from './type-cast/as-struct';
export * from './type-cast/as-union';
export * from './type-cast/as-recursive';
export * from './type-check/is-json';
export * from './type-check/is-primitive';
export * from './type-check/is-struct';
export * from './type-check/is-union';
export * from './type-check/is-recursive';
export * from './type-coerce/make-primative';

@@ -15,2 +19,2 @@ export { Index, Indexable } from './Index.type';

export { InterfacePattern } from './InterfacePattern.type';
export { TypeAssert } from './TypeAssert.type';
export { TypeCheck } from './TypeCheck.type';
import type { Dictionary } from './Dictionary.type';
import type { TypeAssert, UnwrapTypeAssert } from './TypeAssert.type';
export declare type InterfacePattern = Dictionary<TypeAssert<unknown>>;
import type { TypeCheck, UnwrapTypeCheck } from './TypeCheck.type';
export declare type InterfacePattern = Dictionary<TypeCheck<unknown>>;
export declare type UnwrapInterfacePattern<Pattern extends InterfacePattern> = {
[K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>;
[K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>;
};

@@ -1,3 +0,1 @@

import type { Dictionary } from './Dictionary.type';
import type { UnknownFunction } from './UnknownFunction.type';
export declare function memoize<P extends (UnknownFunction | Dictionary), R>(fn: (par: P) => R): (par: P) => R;
export declare function memoize<P extends object, R>(fn: (par: P) => R): (par: P) => R;
import type { JSONValue, JSONArray, JSONObject } from '../JSONValue.type';
import { OptionalTypeCast, TypeCast } from '../TypeCast.type';
import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
export declare const asJSONValue: (obj: unknown, fallback?: import("..").Optional<string | number | boolean | JSONObject | JSONArray>) => JSONValue;

@@ -4,0 +4,0 @@ export declare const asJSONArray: TypeCast<JSONArray, JSONValue>;

@@ -1,2 +0,1 @@

import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
import type { Optional } from '../Optional.type';

@@ -9,16 +8,12 @@ export declare const asString: (obj: unknown, fallback?: string | undefined) => string;

export declare const asArray: (obj: unknown, fallback?: unknown[] | undefined) => unknown[];
export declare const asRecord: (obj: unknown, fallback?: Record<string, unknown> | undefined) => Record<string, unknown>;
export declare const asDictionary: (obj: unknown, fallback?: Record<string, unknown> | undefined) => Record<string, unknown>;
export declare const asFunction: (obj: unknown, fallback?: import("..").UnknownFunction<unknown> | undefined) => import("..").UnknownFunction<unknown>;
export declare function asDefined<T>(obj: Optional<T>, fallback?: NonNullable<T>): NonNullable<T>;
export declare const asOptString: OptionalTypeCast<string, unknown>;
export declare const asOptNumber: OptionalTypeCast<number, unknown>;
export declare const asOptIndex: OptionalTypeCast<import("..").Index, unknown>;
export declare const asOptIndexable: OptionalTypeCast<Record<import("..").Index, unknown>, unknown>;
export declare const asOptBoolean: OptionalTypeCast<boolean, unknown>;
export declare const asOptArray: OptionalTypeCast<unknown[], unknown>;
export declare const asOptRecord: OptionalTypeCast<Record<string, unknown>, unknown>;
export declare const asOptFunction: OptionalTypeCast<import("..").UnknownFunction<unknown>, unknown>;
export declare const asArrayRecursive: <T>(par: (obj: unknown) => T) => TypeCast<T[], unknown>;
export declare const asRecordRecursive: <T>(par: (obj: unknown) => T) => TypeCast<Record<string, T>, unknown>;
export declare const asOptArrayRecursive: <T>(par: (obj: unknown) => T) => OptionalTypeCast<T[], unknown>;
export declare const asOptRecordRecursive: <T>(par: (obj: unknown) => T) => OptionalTypeCast<Record<string, T>, unknown>;
export declare const asOptString: import("../TypeCast.type").OptionalTypeCast<string, unknown>;
export declare const asOptNumber: import("../TypeCast.type").OptionalTypeCast<number, unknown>;
export declare const asOptIndex: import("../TypeCast.type").OptionalTypeCast<import("..").Index, unknown>;
export declare const asOptIndexable: import("../TypeCast.type").OptionalTypeCast<Record<import("..").Index, unknown>, unknown>;
export declare const asOptBoolean: import("../TypeCast.type").OptionalTypeCast<boolean, unknown>;
export declare const asOptArray: import("../TypeCast.type").OptionalTypeCast<unknown[], unknown>;
export declare const asOptDictionary: import("../TypeCast.type").OptionalTypeCast<Record<string, unknown>, unknown>;
export declare const asOptFunction: import("../TypeCast.type").OptionalTypeCast<import("..").UnknownFunction<unknown>, unknown>;

@@ -1,2 +0,2 @@

export declare const asStruct: <Pattern extends Record<string, import("..").TypeAssert<unknown>>>(par: Pattern) => (obj: unknown, fallback?: { [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; } | undefined) => { [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; };
export declare const asOptStruct: <Pattern extends Record<string, import("..").TypeAssert<unknown>>>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeAssert.type").UnwrapTypeAssert<Pattern[K]>; }, unknown>;
export declare const asStruct: <Pattern extends Record<string, import("..").TypeCheck<unknown>>>(par: Pattern) => (obj: unknown, fallback?: { [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; } | undefined) => { [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; };
export declare const asOptStruct: <Pattern extends Record<string, import("..").TypeCheck<unknown>>>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;
import type { Optional } from '../Optional.type';
import type { TypeAssert } from '../TypeAssert.type';
import type { TypeCheck } from '../TypeCheck.type';
import type { OptionalTypeCast } from '../TypeCast.type';
export declare function optTypeCast<Input, Output>(isType: TypeAssert<Output>): OptionalTypeCast<Output, Optional<Input>>;
export declare function typeCast<Output>(isType: TypeAssert<Output>): (obj: unknown, fallback?: Output) => Output;
export declare function optTypeCast<Input, Output>(isType: TypeCheck<Output>): OptionalTypeCast<Output, Optional<Input>>;
export declare function typeCast<Output>(isType: TypeCheck<Output>): (obj: unknown, fallback?: Output) => Output;

@@ -6,8 +6,8 @@ import type { Index, Indexable } from '../Index.type';

import type { UnknownFunction } from '../UnknownFunction.type';
export declare function isRecord(obj: unknown): obj is Dictionary;
export declare namespace isRecord {
export declare function isDictionary(obj: unknown): obj is Dictionary;
export declare namespace isDictionary {
var TYPE_NAME: string;
}
export declare function isOptRecord(obj: unknown): obj is Optional<Dictionary>;
export declare namespace isOptRecord {
export declare function isOptDictionary(obj: unknown): obj is Optional<Dictionary>;
export declare namespace isOptDictionary {
var TYPE_NAME: string;

@@ -14,0 +14,0 @@ }

@@ -1,8 +0,8 @@

import type { TypeAssert, UnwrapTypeAssert } from '../TypeAssert.type';
import type { TypeCheck, UnwrapTypeCheck } from '../TypeCheck.type';
import type { Optional } from '../Optional.type';
export declare const isStruct: <Pattern extends Record<string, TypeAssert<unknown>>>(par: Pattern) => TypeAssert<{ [K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>; }> & {
export declare const isStruct: <Pattern extends Record<string, TypeCheck<unknown>>>(par: Pattern) => TypeCheck<{ [K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>; }> & {
TYPE_NAME: string;
};
export declare const isOptStruct: <Pattern extends Record<string, TypeAssert<unknown>>>(par: Pattern) => TypeAssert<Optional<{ [K in keyof Pattern]: UnwrapTypeAssert<Pattern[K]>; }>> & {
export declare const isOptStruct: <Pattern extends Record<string, TypeCheck<unknown>>>(par: Pattern) => TypeCheck<Optional<{ [K in keyof Pattern]: UnwrapTypeCheck<Pattern[K]>; }>> & {
TYPE_NAME: string;
};
{
"name": "ts-runtime-typecheck",
"version": "1.2.0",
"version": "2.0.0",
"description": "A collection of common types for TypeScript along with dynamic type cast methods.",

@@ -18,3 +18,3 @@ "main": "cjs/index.js",

"author": "Iain Shorter",
"license": "MIT",
"license": "MPL-2.0",
"devDependencies": {

@@ -21,0 +21,0 @@ "@types/jest": "^26.0.14",

# ts-runtime-typecheck
A collection of TypeScript functions for converting unknown values into strictly typed values.
![100% coverage](https://img.shields.io/badge/coverage-100%25-success)
![100% coverage](https://img.shields.io/badge/dependencies-0-success)
![npm](https://img.shields.io/npm/dm/ts-runtime-typecheck)
Simple functions for validating complex data.
JavaScript is a very flexible language. Meaning it's easy to get tripped up by a value with an unexpected type. Even in TypeScript you occasionally have to deal with values which cannot be safely typed at compile time. This library provides a comprehensive selection of functions to simplify type checking code with clear and concise function calls. Ensuring strict type safety throughout your program, no matter the input.
## Installation
Releases are available on the npm repository and our GitHub releases page. ESM and CJS formats are both included, as well as TypeScript type definition files. Both formats work without TypeScript if you prefer plain JS.
```bash
npm install ts-runtime-typecheck
```
---
## Contents

@@ -10,8 +26,10 @@

- [Fallback values](#fallback-values)
- [Special case: asDefined](#special-case-asdefined)
- [Special case: asStruct](#special-case-asstruct)
- [Recursive Array/Object casts](#recursive-arrayobject-casts)
- [Type Checks](#type-checks)
- [Type Coerce](#type-coerce)
- [JSON Types](#json-types)
- [Ensuring an optional value is defined](#ensuring-an-optional-value-is-defined)
- [Array/Object of Type Casts](#arrayobject-of-type-casts)
- [Validating interfaces](#validating-interfaces)
- [Union types](#union-types)
- [Class instances](#class-instances)
- [Reference](#reference)

@@ -29,14 +47,7 @@ - [Reference: Type Casts](#reference-type-casts)

- [v1.2.0](#v120)
- [v2.0.0](#v200)
## Installation
```bash
npm install ts-runtime-typecheck
```
---
## Type Casts
**Type Casts** take an `unknown` object as an argument, and return a typed object as the result. These functions take the form [`as{TYPE}`](#reference-type-casts), for example [`asNumber`](#asNumber). If the input object does not match the required type the function will throw. This does not perform any coercion on the value, passing a `string` of a number to [`asNumber`](#asNumber) will cause it to throw.
**Type Casts** take an `unknown` value as an argument, and return a typed value as the result. These functions take the form [`as{TYPE}`](#reference-type-casts), for example [`asNumber`](#asNumber). If the input value does not match the required type the function will throw. This does not perform any coercion on the value, passing a `string` of a number to [`asNumber`](#asNumber) will cause it to throw.

@@ -81,98 +92,4 @@ ```typescript

In the situation you want to preserve the optionally of a value, but still validate the type there exists an alternate function for each type cast. These take the form [`asOpt{TYPE}`](#reference-optional-type-casts). Unlike the standard methods they do not take an optional fallback value, but when a [`Nullish`](#nullish) value is passed in they will always emit `undefined`. If the input is not [`Nullish`](#nullish), then it behaves the same as the standard type casts. If the type condition is met then it emits the value, otherwise it will throw.
In the situation you want to check a value meets an [`Optional`](#optional) type there exists an alternate function for each type cast. These take the form [`asOpt{TYPE}`](#reference-optional-type-casts). Unlike the standard functions they do not allow for a fallback value, but when a [`Nullish`](#nullish) value is passed in they will always emit `undefined`. If the input is not [`Nullish`](#nullish), then it behaves the same as the standard type casts. If the type condition is met then it emits the value, otherwise it will throw.
### Special case: asDefined
Another common situation is that you have an [`Optional`](#optional) value, with a well defined type, but it *shouldn't* be [`Optional`](#optional) at that time. TypeScript will allow you to cast the value to a non-optional type using `!`, but this is often discouraged in style guides as it can hide real errors. This is solved by the [`asDefined`](#asdefined) function, which removes the optionality from a type union. As with the other type casts this can take a fallback value, and will throw if the condition is not met. However, the output type matches the input type with [`Nullish`](#nullish) subtracted.
```typescript
import { asDefined } from 'ts-runtime-typecheck';
function setup (useComplexType: boolean = false, complexInst?: ComplexType) {
if (useComplexType) {
const inst: ComplexType = asDefined(complexInst);
inst.doComplexThing();
}
else {
doSimpleThing();
}
}
```
### Special case: asStruct
Validating the shape of an object using a combination of [`asRecord`](#asrecord) and other [Type Casts](#reference-type-casts) specific to property types can be a bit verbose. To simplify this scenario you can use [`asStruct`](#asstruct). This function takes an [`InterfacePattern`](#interfacepattern) that specifies a specific structure and returns a new function that will cast an unknown value to that structure. An [`InterfacePattern`](#interfacepattern is a fancy name for a [`Dictionary`](#dictionary) of [Type Check](#reference-type-checks) functions.
```typescript
import { asStruct, isString, isOptString, isNumber } from 'ts-runtime-typecheck';
interface Item {
name: string;
value: number;
}
const asItem = asStruct({ name: isString, value: isNumber })
function main (obj: unknown) {
const item: Item = asItem(obj);
console.log(`${item.name} = ${item.value}`);
}
```
There is also a [Type Check](#reference-type-checks) variant of the this function called [`isStruct`](#isstruct) which works in a very similar way. As an [`InterfacePattern`](#interfacepattern) is composed of [Type Check](#reference-type-checks) functions it's possible to compose nested structure checks.
```typescript
import { asStruct, isString, isOptString, isNumber } from 'ts-runtime-typecheck';
interface Declaration {
item: Item;
description: Optional<string>
}
const isItem = isStruct({ name: isString, value: isNumber });
const asDeclaration = asStruct({ item: isItem, description: isOptString });
function main (obj: unknown) {
const { item, description } = asDeclaration(obj);
const comment: string = description ? `// ${description}` : '';
console.log(`${item.name} = ${item.value} ${comment}`);
}
```
### Recursive Array/Object Casts
Validating that a value is an array or object is easy enough, but how about the contents? [`asArrayRecursive`](#asarrayrecursive) and [`asObjectRecursive`](#asobjectrecursive) allow for deep type casting through a user specified element cast. For example, to cast to `Array<string>`:
```typescript
import { asString, asArrayRecursive } from 'ts-runtime-typecheck';
function main (obj: unknown) {
const asStringArray = asArrayRecursive(asString);
const arr: string[] = asStringArray(obj);
}
```
Or `Array<Dictionary<number>>`:
```typescript
import { asNumber, asRecordRecursive, asArrayRecursive } from 'ts-runtime-typecheck';
function main () {
const asNumericRecord = asRecordRecursive(asNumber);
const asArrayOfNumericRecords = asArrayRecursive(asNumericRecord);
const arr = asArrayOfNumericRecords([
{
a: 12,
b: 42
},
{
n: 90
}
]);
}
```
---

@@ -182,3 +99,3 @@

[Type Checks](#reference-type-checks) take an `unknown` object as an argument, and return a `boolean` indicating if the given value matches the required type. These functions take the form [`is{TYPE}`](#reference-type-checks) In the correct situation TypeScript is capable of refining the type of a value through the use of these functions and flow analysis, like the below example.
**Type Checks** take an `unknown` value as an argument, and return a `boolean` indicating if the given value matches the required type. These functions take the form [`is{TYPE}`](#reference-type-checks). In the correct situation TypeScript is capable of refining the type of a value through the use of these functions and flow analysis, like the below example.

@@ -222,3 +139,3 @@ ```typescript

Type coercion functions take an unknown object as an argument, and convert it into a specific type. These functions take the format [`make{TYPE}`](#reference-type-coerce). Unlike the other functions this only works for small subset of types: number, string and boolean. They make a best effort to convert the type, but if the input is not suitable then they will throw. For instance passing a non-numeric string to [`makeNumber`](#make-number) will cause it to throw, as will passing a string that is not `"true" | "false"` to [`makeBoolean`](#make-boolean). While these functions will take any input value, this is to allow the input of values that have not been validated, actually the only valid input types for all 3 functions are `number | string | boolean`. The intention here is to allow useful conversion, but prevent accidentally passing complex types.
**Type Coercion** functions take an `unknown` value as an argument, and convert it into a specific type. These functions take the format [`make{TYPE}`](#reference-type-coerce). Unlike the other functions this only works for small subset of types: number, string and boolean. They make a best effort to convert the type, but if the input is not suitable then they will throw an error. For instance passing a non-numeric string to [`makeNumber`](#make-number) will cause it to throw, as will passing a string that is not `"true" | "false"` to [`makeBoolean`](#make-boolean). While these functions will take any input value, this is to allow the input of values that have not been validated. The only valid input types for all 3 functions are `number | string | boolean`. The intention here is to allow useful conversion, but prevent accidentally passing complex types.

@@ -245,3 +162,3 @@ There is an argument that [`makeString`](#makestring) could support using the `toString` method of an `object`, but the default `toString` method returns the useless `[object Object]` string. It is possible to detect if an object has implemented it's own `toString` method, but is it correct to use it in this situation? That depends on the intention of the programmer. In the absence of a clear answer the line has been drawn at only accepting primitives.

Dealing with validating JSON objects can often be frustrating, so to make it a little easier JSON specific types and checks are provided. Using the [`JSONValue`](#jsonvalue) type in your code will ensure that TS statically analyses any literal values as serializable to JSON.
Dealing with validating JSON values can often be frustrating, so to make it a little easier JSON specific types and checks are provided. Using the [`JSONValue`](#jsonvalue) type in your code will ensure that TS statically analyses any literal values as serializable to JSON.

@@ -266,3 +183,3 @@ ```typescript

Type checks and casts are provided for [`JSONArray`](#jsonarray)s and [`JSONObject`](#jsonobject)s, with the caveat that they only accept [`JSONValue`](#jsonvalue)s. This is to avoid needing to recursively validate the object.
[Type Check](#reference-type-checks) and [Type Casts](#reference-type-casts) are provided for [`JSONArrays`](#jsonarray) and [`JSONObjects`](#jsonobject), with the caveat that they only accept [`JSONValues`](#jsonvalue). This is to avoid needing to recursively validate values which have already been validated.

@@ -288,3 +205,3 @@ ```typescript

One other caveat of [`JSONValue`](#jsonvalue) is that it does not guarantee that the value is not cyclic. It is not possible to serialize cyclic object with JSON, but they are otherwise valid. Using [`isJSONValue`](#isjsonvalue) or [`asJSONValue`](#asjsonvalue) on a cyclic object *will fail*.
One other caveat of [`JSONValue`](#jsonvalue) is that it does not guarantee that the value is not cyclic. It is not possible to serialize cyclic object with `JSON.stringify`, but they are otherwise valid. Using [`isJSONValue`](#isjsonvalue) or [`asJSONValue`](#asjsonvalue) on a cyclic object *will fail*.

@@ -304,2 +221,146 @@ ```typescript

## Ensuring an optional value is defined
A common situation is that you have an [`Optional`](#optional) value, with a well defined type. At a specific time it should be defined, but the type system is not aware of this. TypeScript will allow you to cast the value to a non-optional type using `!`, but this is often discouraged in style guides. As an alternative solution you can use the [`asDefined`](#asdefined) function, which removes the optionality from a type union. As with the other type casts this can take a fallback value, and will throw if the condition is not met. However, the output type matches the input type with [`Nullish`](#nullish) subtracted.
```typescript
import { asDefined } from 'ts-runtime-typecheck';
function setup (useComplexType: boolean = false, complexInst?: ComplexType) {
if (useComplexType) {
const inst: ComplexType = asDefined(complexInst);
inst.doComplexThing();
}
else {
doSimpleThing();
}
}
```
## Array/Object of Type Casts
Validating that a value is an array or dictionary is easy enough, but how about the type of the contents? [`asArrayOf`](#asarrayof) and [`asDictionaryOf`](#asdictionaryof) allow you to cast the elements of a collection using a user defined [Type Check](#reference-type-checks). For example, to cast to `Array<string>`:
```typescript
import { isString, asArrayOf } from 'ts-runtime-typecheck';
function main (obj: unknown) {
const asStringArray = asArrayOf(isString);
const arr: string[] = asArrayOfString(obj);
}
```
Or `Array<Dictionary<number>>`:
```typescript
import { isNumber, isDictionaryOf, asArrayOf } from 'ts-runtime-typecheck';
function main () {
const isDictionaryOfNumber = isDictionaryOf(isNumber);
const asArrayOfDictionaryOfNumber = asArrayOf(isDictionaryOfNumber);
const arr = asArrayOfDictionaryOfNumber([
{
a: 12,
b: 42
},
{
n: 90
}
]);
}
```
## Validating interfaces
Validating the shape of an object using a combination of [`asDictionary`](#asdictionary) and other [Type Casts](#reference-type-casts) specific to property types can be a bit verbose. To simplify this scenario you can use [`asStruct`](#asstruct). This function takes an [`InterfacePattern`](#interfacepattern) that defines a specific structure and returns a new function that will cast an unknown value to that structure. An [`InterfacePattern`](#interfacepattern) is a fancy name for a [`Dictionary`](#dictionary) of [Type Checks](#reference-type-checks).
```typescript
import { asStruct, isString, isOptString, isNumber } from 'ts-runtime-typecheck';
interface Item {
name: string;
value: number;
}
const asItem = asStruct({ name: isString, value: isNumber })
function main (obj: unknown) {
const item: Item = asItem(obj);
console.log(`${item.name} = ${item.value}`);
}
```
There is also a [Type Check](#reference-type-checks) variant of the this function called [`isStruct`](#isstruct) which works in a very similar way. As an [`InterfacePattern`](#interfacepattern) is composed of [Type Check](#reference-type-checks) functions it's possible to compose nested interface [Type Checks](#reference-type-checks).
```typescript
import { asStruct, isString, isOptString, isNumber } from 'ts-runtime-typecheck';
interface Declaration {
item: Item;
description: Optional<string>
}
const isItem = isStruct({ name: isString, value: isNumber });
const asDeclaration = asStruct({ item: isItem, description: isOptString });
function main (obj: unknown) {
const { item, description } = asDeclaration(obj);
const comment: string = description ? `// ${description}` : '';
console.log(`${item.name} = ${item.value} ${comment}`);
}
```
---
## Union types
When a value can be 2 or more types it is relatively easy to do [Type Check](#reference-type-checks).
```typescript
import { isString, isArray } from 'ts-runtime-typecheck';
if (isString(a) || isArray(a)) {
// a: string | unknown[]
}
```
But you can't cast to that type, or pass it into a function like [`asArrayOf`](#asarrayof) or [`isStruct`](isstruct) which require a [Type Check](#reference-type-checks) for their input. To do this you can use [`isUnion`](#isunion) or [`asUnion`](#asunion). These functions take a variable number of [Type Checks](#reference-type-checks) and produce a union of them.
```typescript
import {
isString,
isArray,
isUnion,
asArrayOf
} from 'ts-runtime-typecheck';
const check = asArrayOf(isUnion(isString, isArray));
const b = check(['hello', [0, 1, 2], 'world']);
```
---
## Class instances
Under most scenarios you will know if a value is an instance of a given class. However, there are scenarios where this is not the case. For these situations you can use [`isInstance`](#isinstance) or [`asInstance`](#asinstance) to ensure you have the correct type.
```typescript
import { isInstance } from 'ts-runtime-typecheck';
function print_error (err) {
if (isInstance(Error)(err)) {
print_string(err.message);
} else {
print_unknown(err)
}
}
```
When validating a value matches an interface it may be desirable to instead use [`isInstance`](#isinstance) instead of [`isStruct`](#isstruct). While it doesn't provide the same guarantees it will often be significantly faster, as it does not perform a [Type Check](#reference-type-checks) on each member to see that they exist and contain the right type of value.
---
## Reference

@@ -333,3 +394,3 @@

- ### asRecord
- ### asDictionary

@@ -358,14 +419,18 @@ Cast `unknown` to [`Dictionary<unknown>`](#dictionary). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.

- ### asArrayRecursive
- ### asArrayOf
Takes a Type Cast function for `Type` and returns a new Type Cast function for `Array<Type>` where type is a generic parameter. The emitted Type Cast function accepts an optional fallback value that is emitted if the value is nullish and fallback is defined. Refer to [Recursive Array/Object casts](#recursive-arrayobject-casts) for examples.
Takes a Type Cast function for `Type` and returns a new Type Cast function for `Array<Type>` where type is a generic parameter. The emitted Type Cast function accepts an optional fallback value that is emitted if the value is nullish and fallback is defined. Refer to [Array/Object of Type Casts](#arrayobject-of-type-casts) for examples.
- ### asObjectRecursive
- ### asDictionaryOf
Takes a Type Cast function for `Type` and returns a new Type Cast function for [`Dictionary<Type>`](#dictionary) where type is a generic parameter. The emitted Type Cast function accepts an optional fallback value that is emitted if the value is nullish and fallback is defined. Refer to [Recursive Array/Object casts](#recursive-arrayobject-casts) for examples.
Takes a Type Cast function for `Type` and returns a new Type Cast function for [`Dictionary<Type>`](#dictionary) where type is a generic parameter. The emitted Type Cast function accepts an optional fallback value that is emitted if the value is nullish and fallback is defined. Refer to [Array/Object of Type Casts](#arrayobject-of-type-casts) for examples.
- ### asStruct
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new Type Cast function for `Type`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Special Case: asStruct](#special-case-asstruct) for examples.
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new Type Cast function for `Type`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Validating interfaces](#validating-interfaces) for examples.
- ### asInstance
Takes a class (not a instance of a class) and returns a new Type Cast for an instance of that class.
### Reference: Optional Type Casts

@@ -397,3 +462,3 @@

- ### asOptRecord
- ### asOptDictionary

@@ -406,2 +471,10 @@ Cast `unknown` value to [`Dictionary<unknown> | undefined`](#dictionary). If value is [`Nullish`](#nullish) then return `undefined`.

- ### asUnion
Takes a variable number of type checks as parameters `<A>(...checks: TypeCheck<A>[])` and returns a new type cast that composes them into type cast for the union `A`. This allows creating a cast for a type union by composing any existing type checks.
- ### asOptUnion
Identical to [`asUnion`](#asunion) but it the resulting cast returns `A | null | undefined`.
- ### asOptJSONValue

@@ -419,17 +492,21 @@

- ### asOptArrayRecursive
- ### asOptArrayOf
Takes a Type Cast function for `Type` and returns a new Type Cast function for `Array<Type> | undefined` where type is a generic parameter. Refer to [Recursive Array/Object casts](#recursive-arrayobject-casts) for examples.
Takes a Type Cast function for `Type` and returns a new Type Cast function for `Array<Type> | undefined` where type is a generic parameter. Refer to [Array/Object of Type Casts](#arrayobject-of-type-casts) for examples.
- ### asOptRecordRecursive
- ### asOptDictionaryOf
Takes a Type Cast function for `Type` and returns a new Type Cast function for [`Dictionary<Type> | undefined`](#dictionary) where type is a generic parameter. Refer to [Recursive Array/Object casts](#recursive-arrayobject-casts) for examples.
Takes a Type Cast function for `Type` and returns a new Type Cast function for [`Dictionary<Type> | undefined`](#dictionary) where type is a generic parameter. Refer to [Array/Object of Type Casts](#arrayobject-of-type-casts) for examples.
- ### asOptStruct
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new Type Cast function for `Type | undefined`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Special Case: asStruct](#special-case-asstruct) for examples.
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new Type Cast function for `Type | undefined`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Validating interfaces](#validating-interfaces) for examples.
- ### asOptInstance
Takes a class (not a instance of a class) and returns a new Type Cast for a Optional instance of that class.
### Reference: Type Checks
- ### isRecord
- ### isDictionary

@@ -478,2 +555,6 @@ Takes an `unknown` value and returns a boolean indicating if the value is of the type [`Dictionary<unknown>`](#dictionary).

- ### isUnion
Takes a variable number of type checks as parameters `<A>(...checks: TypeCheck<A>[])` and returns a new type check that composes them into union type check `TypeCheck<A>`. This allows creating a test for a type union by composing any existing type checks. For inline code it will generally make sense to use logical OR operators instead of this, for example `if ( isNumber(n) || isArray(n) ) {}`. This particular function is intended for when you wish to compose a type check or cast that contains a union, or create a library type check for a common union type.
- ### isJSONValue

@@ -491,10 +572,22 @@

### Reference: Optional Type Checks
- ### isArrayOf
Takes a Type Check function for `Type` and returns a new Type Check function for `Array<Type>` where Type is a generic parameter.
- ### isDictionaryOf
Takes a Type Check function for `Type` and returns a new Type Check function for [`Dictionary<Type>`](#dictionary) where Type is a generic parameter.
- ### isStruct
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new [`TypeAssert`](#typeassert) function for `Type`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Special Case: asStruct](#special-case-asstruct) for examples.
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new [`TypeAssert`](#typeassert) function for `Type`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Validating interfaces](#validating-interfaces) for examples.
- ### isOptRecord
- ### isInstance
Takes a class (not a instance of a class) and returns a new Type Check for an instance of that class.
### Reference: Optional Type Checks
- ### isOptDictionary
Takes an `unknown` value and returns a boolean indicating if the value is of the type [`Optional<Dictionary<unknown>>`](#dictionary).

@@ -530,2 +623,6 @@

- ### isOptUnion
Identical to [`isUnion`](#isunion) but it the resulting typecheck is `TypeCheck<A | null | undefined>`.
- ### isOptJSONValue

@@ -545,4 +642,16 @@

Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new [`TypeAssert`](#typeassert) function for `Optional<Type>`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Special Case: asStruct](#special-case-asstruct) for examples.
Takes an [`InterfacePattern`](#interfacepattern) which is equivalent to `Type` and returns a new [`TypeAssert`](#typeassert) function for `Optional<Type>`, where `Type` is an interface defined by the [`TypeAsserts`](#typeassert) specified in the pattern. Refer to [Validating interfaces](#validating-interfaces) for examples.
- ### isOptArrayOf
Takes a Type Check function for `Type` and returns a new Type Check function for `Optional<Array<Type>>` where Type is a generic parameter.
- ### isOptDictionaryOf
Takes a Type Check function for `Type` and returns a new Type Check function for [`Optional<Dictionary<Type>>`](#dictionary) where Type is a generic parameter.
- ### isOptInstance
Takes a class (not a instance of a class) and returns a new Type Check for a Optional instance of that class.
### Reference: Type Coerce

@@ -552,11 +661,11 @@

Takes an `unknown` value and converts it to it's *textual* representation. A value that cannot be cleaning converted will trigger an error.
Takes an `unknown` value and converts it to it's *textual* representation. A value that cannot be cleanly converted will trigger an error.
- ### makeNumber
Takes an `unknown` value and converts it to it's *numerical* representation. A value that cannot be cleaning converted will trigger an error.
Takes an `unknown` value and converts it to it's *numerical* representation. A value that cannot be cleanly converted will trigger an error.
- ### makeBoolean
Takes an `unknown` value and converts it to it's *boolean* representation. A value that cannot be cleaning converted will trigger an error.
Takes an `unknown` value and converts it to it's *boolean* representation. A value that cannot be cleanly converted will trigger an error.

@@ -599,3 +708,3 @@ ### Reference: Types

A stricter alternative to the type `Function`. It accepts any number of unknown parameters, and returns an unknown valid. Allowing you to reference an untyped function in a slightly safer manner. This does not provide any arity or type checks for the parameters.
A stricter alternative to the type `Function`. It accepts any number of unknown parameters, and returns an unknown value. Allowing you to reference an untyped function in a slightly safer manner. This does not provide any arity or type checks for the parameters.

@@ -606,9 +715,9 @@ - ### UnknownAsyncFunction

- ### TypeAssert
- ### TypeCheck
An alias for a function that meets the requirements of TypeScript [Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards). They take the format `(value: unknown) => value is TYPE`. With the except of specialist JSON checks all [Type Checks](#reference-type-checks) conform to this type.
An alias for a function that meets the requirements of TypeScript [Type Guards](https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards). They take the format `(value: unknown) => value is TYPE`. With the exception of specialist JSON checks all [Type Checks](#reference-type-checks) conform to this type.
- ### InterfacePattern
An alias for a [`Dictionary`](#dictionary) of [`TypeAssert`](#typeassert) functions. When used in conjunction with [`isStruct`](#isstruct) or [`asStruct`](#asstruct) they can validate an `object` again the equivalent interface to the pattern.
An alias for a [`Dictionary`](#dictionary) of [`TypeAssert`](#typeassert) functions. When used in conjunction with [`isStruct`](#isstruct) or [`asStruct`](#asstruct) they can validate an `object` against the equivalent interface to the pattern.

@@ -638,8 +747,21 @@ ## Changelog

- Add: Introduce `isStruct` and `asStruct` that allow the inspection of a object to see if it meets a specific interface.
- Add: Optional variants of Type Checks with form `isOpt{TYPE}`.
- Change: `asDefined` can longer accept `null` as a fallback parameter.
- Add: Optional variants of [Type Checks](#reference-type-checks) with form `isOpt{TYPE}`.
- Breaking Change: `asDefined` can longer accept `null` as a fallback parameter.
- Change: `asIndexable` now accepts arrays.
- Add: `isIndexable` type check.
- Add: `isIndexable` [type check](#reference-type-checks).
- Change: Expose the `TypeAssert` type publicly.
- Add: `InterfacePattern` type.
- Change: modify the type names in errors to be closer to the TypeScript names.
### v2.0.0
- Add: `isUnion` and `isOptUnion` to allow checking if a value matches any type of a type union.
- Add: `asUnion` and `asOptUnion` to allow casting a value to a type union.
- Add: `isArrayOf` and `isOptArrayOf` to allow checking if a value is an array of a given type.
- Add: `isDictionaryOf` and `isOptDictionaryOf` to allow checking if a value is a Dictionary of a given type.
- Breaking Change: Recursive [Type Casts](#reference-type-casts) now take a [Type Check](#reference-type-checks) as an argument instead of a [Type Cast](#reference-type-casts), and no longer emit a copy of the input. As a side effect if you are upgrading from `asArrayRecursive(asOptString)` to `asArraryOf(isOptString)` or (similar) the output array may contain `null` as the elements are no longer transformed by an inner cast ( optional cast methods normalize output to `undefined` ).
- Add: `isInstance` and `isOptInstance` to allow checking if a value is an instance of a given class.
- Add: `asInstance` and `asOptInstance` to allow casting a value to an instance of a given class.
- Breaking Change: `asRecord`, `asOptRecord`, `asRecordRecursive` and `asOptRecordRecursive` have been renamed to `asDictionary`, `asOptDictionary`, `asDictionaryOf` and `asOptDictionaryOf` respectively.
- Breaking Change: `asArrayRecursive` and `asOptArrayRecursive` have been renamed to `asArrayOf` and `asOptArrayOf` respectively.
- Breaking Change: rename `TypeAssert` to `TypeCheck`

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc