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 2.5.0 to 2.6.0

cjs/type-cast/as-guarded-function.d.ts

1

cjs/index.d.ts

@@ -8,2 +8,3 @@ export * from './type-cast/as-json';

export * from './type-cast/as-literal';
export * from './type-cast/as-guarded-function';
export * from './type-check/is-json';

@@ -10,0 +11,0 @@ export * from './type-check/is-primitive';

@@ -12,2 +12,3 @@ 'use strict';

var asLiteral = require('./type-cast/as-literal.js');
var asGuardedFunction = require('./type-cast/as-guarded-function.js');
var isJson = require('./type-check/is-json.js');

@@ -68,2 +69,3 @@ var isPrimitive = require('./type-check/is-primitive.js');

exports.asOptLiteral = asLiteral.asOptLiteral;
exports.asGuardedFunction = asGuardedFunction.asGuardedFunction;
exports.isJSONArray = isJson.isJSONArray;

@@ -70,0 +72,0 @@ exports.isJSONObject = isJson.isJSONObject;

2

cjs/invariant.d.ts

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

export declare function invariant(condition: boolean, msg: string): asserts condition;
export declare function invariant(isValid: boolean, msg: string): asserts isValid;
//# sourceMappingURL=invariant.d.ts.map

@@ -7,4 +7,4 @@ 'use strict';

function invariant(condition, msg) {
if (!condition) {
function invariant(isValid, msg) {
if (!isValid) {
throw new TypeAssertion.TypeAssertion(msg);

@@ -11,0 +11,0 @@ }

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

@@ -5,0 +5,0 @@ export declare const asJSONObject: TypeCast<JSONObject, JSONValue>;

import type { Optional } from '../Optional.type';
export declare const asString: (obj: unknown, fallback?: string | undefined) => string;
export declare const asNumber: (obj: unknown, fallback?: number | undefined) => number;
export declare const asIndex: (obj: unknown, fallback?: import("..").Index | undefined) => import("..").Index;
export declare const asIndexable: (obj: unknown, fallback?: import("..").Indexable | undefined) => import("..").Indexable;
export declare const asPrimitive: (obj: unknown, fallback?: import("..").Primitive | undefined) => import("..").Primitive;
export declare const asBoolean: (obj: unknown, fallback?: boolean | undefined) => boolean;
export declare const asArray: (obj: unknown, fallback?: unknown[] | undefined) => unknown[];
export declare const asDictionary: (obj: unknown, fallback?: import("..").Dictionary<unknown> | undefined) => import("..").Dictionary<unknown>;
export declare const asFunction: (obj: unknown, fallback?: import("..").UnknownFunction<unknown> | undefined) => import("..").UnknownFunction<unknown>;
export declare const asString: import("../TypeCast.type").TypeCast<string, unknown>;
export declare const asNumber: import("../TypeCast.type").TypeCast<number, unknown>;
export declare const asIndex: import("../TypeCast.type").TypeCast<import("..").Index, unknown>;
export declare const asIndexable: import("../TypeCast.type").TypeCast<import("..").Indexable, unknown>;
export declare const asPrimitive: import("../TypeCast.type").TypeCast<import("..").Primitive, unknown>;
export declare const asBoolean: import("../TypeCast.type").TypeCast<boolean, unknown>;
export declare const asArray: import("../TypeCast.type").TypeCast<unknown[], unknown>;
export declare const asDictionary: import("../TypeCast.type").TypeCast<import("..").Dictionary<unknown>, unknown>;
export declare const asFunction: import("../TypeCast.type").TypeCast<import("..").UnknownFunction<unknown>, unknown>;
export declare function asDefined<T>(obj: Optional<T>): NonNullable<T>;
export declare function asDefined<T>(obj: Optional<T>, fallback?: NonNullable<T>): NonNullable<T>;

@@ -12,0 +13,0 @@ export declare const asOptString: import("../TypeCast.type").OptionalTypeCast<string, unknown>;

import type { InterfacePattern } from '../InterfacePattern.type';
export declare const asStruct: <Pattern extends InterfacePattern>(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 asStruct: <Pattern extends InterfacePattern>(par: Pattern) => import("../TypeCast.type").TypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;
export declare const asOptStruct: <Pattern extends InterfacePattern>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;
//# sourceMappingURL=as-struct.d.ts.map
import type { Optional } from '../Optional.type';
import type { TypeCheck } from '../TypeCheck.type';
import type { OptionalTypeCast } from '../TypeCast.type';
import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
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;
export declare function typeCast<Output>(isType: TypeCheck<Output>): TypeCast<Output>;
//# sourceMappingURL=type-cast.d.ts.map

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

var inspectType = require('../inspectType.js');
var TypeCheck = require('../TypeCheck.js');
function optTypeCast(isType) {
return (obj) => {
var _a;
if (isPrimitive.isNullish(obj)) {

@@ -18,3 +18,3 @@ return undefined;

}
throw new Error(`Unable to cast ${inspectType.inspectType(obj)} to Optional<${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}>`);
throw new Error(`Unable to cast ${inspectType.inspectType(obj)} to Optional<${TypeCheck.getTypeName(isType)}>`);
};

@@ -24,3 +24,2 @@ }

return (obj, fallback) => {
var _a;
if (isType(obj)) {

@@ -32,3 +31,3 @@ return obj;

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

@@ -35,0 +34,0 @@ }

@@ -7,33 +7,30 @@ 'use strict';

var isPrimitive = require('./is-primitive.js');
var TypeCheck = require('../TypeCheck.js');
const isDictionaryOf = memoize.memoize((isType) => {
var _a;
const result = (obj) => {
return isPrimitive.isDictionary(obj) && Object.values(obj).every(isType);
};
result.TYPE_NAME = `Dictionary<${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}>`;
result.TYPE_NAME = `Dictionary<${TypeCheck.getTypeName(isType)}>`;
return result;
});
const isOptDictionaryOf = memoize.memoize((isType) => {
var _a;
const result = (obj) => {
return isPrimitive.isNullish(obj) || isPrimitive.isDictionary(obj) && Object.values(obj).every(isType);
};
result.TYPE_NAME = `Optional<Dictionary<${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}>>`;
result.TYPE_NAME = `Optional<Dictionary<${TypeCheck.getTypeName(isType)}>>`;
return result;
});
const isArrayOf = memoize.memoize((isType) => {
var _a;
const result = (obj) => {
return isPrimitive.isArray(obj) && obj.every(isType);
};
result.TYPE_NAME = `${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}[]`;
result.TYPE_NAME = `${TypeCheck.getTypeName(isType)}[]`;
return result;
});
const isOptArrayOf = memoize.memoize((isType) => {
var _a;
const result = (obj) => {
return isPrimitive.isNullish(obj) || isPrimitive.isArray(obj) && obj.every(isType);
};
result.TYPE_NAME = `Optional<${(_a = isType.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'}[]>`;
result.TYPE_NAME = `Optional<${TypeCheck.getTypeName(isType)}[]>`;
return result;

@@ -40,0 +37,0 @@ });

@@ -5,2 +5,3 @@ 'use strict';

var TypeCheck = require('../TypeCheck.js');
var isPrimitive = require('./is-primitive.js');

@@ -10,3 +11,3 @@

const test = (value) => tests.some(test => test(value));
test.TYPE_NAME = tests.map(test => { var _a; return (_a = test.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'; }).join(' | ');
test.TYPE_NAME = tests.map(test => TypeCheck.getTypeName(test)).join(' | ');
return test;

@@ -16,3 +17,3 @@ }

const test = (value) => isPrimitive.isNullish(value) || tests.some(test => test(value));
test.TYPE_NAME = `Optional<${tests.map(test => { var _a; return (_a = test.TYPE_NAME) !== null && _a !== void 0 ? _a : 'unknown'; }).join(' | ')}>`;
test.TYPE_NAME = `Optional<${tests.map(test => TypeCheck.getTypeName(test)).join(' | ')}>`;
return test;

@@ -19,0 +20,0 @@ }

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

export declare class TypeAssertion extends Error {
}
export declare const TypeAssertion: TypeErrorConstructor;
//# sourceMappingURL=TypeAssertion.d.ts.map

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

class TypeAssertion extends Error {
}
const TypeAssertion = TypeError;
exports.TypeAssertion = TypeAssertion;
//# sourceMappingURL=TypeAssertion.js.map
import type { Optional } from './Optional.type';
export declare type TypeCast<Output, Input = unknown> = (value: Input, fallback?: Output) => Output;
export interface TypeCast<Output, Input = unknown> {
(value: Input): Output;
(value: Input, fallback?: Output): Output;
}
export declare type OptionalTypeCast<Output, Input = unknown> = (value: Optional<Input>) => Output | undefined;
//# sourceMappingURL=TypeCast.type.d.ts.map

@@ -7,2 +7,5 @@ export interface TypeCheck<T> {

export declare type UnwrapTypeCheckArray<T extends TypeCheck<unknown>[]> = T extends TypeCheck<infer P>[] ? P : never;
export declare type UnwrapTypeCheckTuple<T extends TypeCheck<unknown>[]> = {
[Index in keyof T]: T[Index] extends TypeCheck<infer P> ? P : never;
};
//# sourceMappingURL=TypeCheck.type.d.ts.map

@@ -8,2 +8,3 @@ export * from './type-cast/as-json';

export * from './type-cast/as-literal';
export * from './type-cast/as-guarded-function';
export * from './type-check/is-json';

@@ -10,0 +11,0 @@ export * from './type-check/is-primitive';

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

export declare function invariant(condition: boolean, msg: string): asserts condition;
export declare function invariant(isValid: boolean, msg: string): asserts isValid;
//# sourceMappingURL=invariant.d.ts.map
import type { JSONValue, JSONArray, JSONObject } from '../JSONValue.type';
import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
export declare const asJSONValue: (obj: unknown, fallback?: JSONValue | undefined) => JSONValue;
export declare const asJSONValue: TypeCast<JSONValue, unknown>;
export declare const asJSONArray: TypeCast<JSONArray, JSONValue>;

@@ -5,0 +5,0 @@ export declare const asJSONObject: TypeCast<JSONObject, JSONValue>;

import type { Optional } from '../Optional.type';
export declare const asString: (obj: unknown, fallback?: string | undefined) => string;
export declare const asNumber: (obj: unknown, fallback?: number | undefined) => number;
export declare const asIndex: (obj: unknown, fallback?: import("..").Index | undefined) => import("..").Index;
export declare const asIndexable: (obj: unknown, fallback?: import("..").Indexable | undefined) => import("..").Indexable;
export declare const asPrimitive: (obj: unknown, fallback?: import("..").Primitive | undefined) => import("..").Primitive;
export declare const asBoolean: (obj: unknown, fallback?: boolean | undefined) => boolean;
export declare const asArray: (obj: unknown, fallback?: unknown[] | undefined) => unknown[];
export declare const asDictionary: (obj: unknown, fallback?: import("..").Dictionary<unknown> | undefined) => import("..").Dictionary<unknown>;
export declare const asFunction: (obj: unknown, fallback?: import("..").UnknownFunction<unknown> | undefined) => import("..").UnknownFunction<unknown>;
export declare const asString: import("../TypeCast.type").TypeCast<string, unknown>;
export declare const asNumber: import("../TypeCast.type").TypeCast<number, unknown>;
export declare const asIndex: import("../TypeCast.type").TypeCast<import("..").Index, unknown>;
export declare const asIndexable: import("../TypeCast.type").TypeCast<import("..").Indexable, unknown>;
export declare const asPrimitive: import("../TypeCast.type").TypeCast<import("..").Primitive, unknown>;
export declare const asBoolean: import("../TypeCast.type").TypeCast<boolean, unknown>;
export declare const asArray: import("../TypeCast.type").TypeCast<unknown[], unknown>;
export declare const asDictionary: import("../TypeCast.type").TypeCast<import("..").Dictionary<unknown>, unknown>;
export declare const asFunction: import("../TypeCast.type").TypeCast<import("..").UnknownFunction<unknown>, unknown>;
export declare function asDefined<T>(obj: Optional<T>): NonNullable<T>;
export declare function asDefined<T>(obj: Optional<T>, fallback?: NonNullable<T>): NonNullable<T>;

@@ -12,0 +13,0 @@ export declare const asOptString: import("../TypeCast.type").OptionalTypeCast<string, unknown>;

import type { InterfacePattern } from '../InterfacePattern.type';
export declare const asStruct: <Pattern extends InterfacePattern>(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 asStruct: <Pattern extends InterfacePattern>(par: Pattern) => import("../TypeCast.type").TypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;
export declare const asOptStruct: <Pattern extends InterfacePattern>(par: Pattern) => import("../TypeCast.type").OptionalTypeCast<{ [K in keyof Pattern]: import("../TypeCheck.type").UnwrapTypeCheck<Pattern[K]>; }, unknown>;
//# sourceMappingURL=as-struct.d.ts.map
import type { Optional } from '../Optional.type';
import type { TypeCheck } from '../TypeCheck.type';
import type { OptionalTypeCast } from '../TypeCast.type';
import type { OptionalTypeCast, TypeCast } from '../TypeCast.type';
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;
export declare function typeCast<Output>(isType: TypeCheck<Output>): TypeCast<Output>;
//# sourceMappingURL=type-cast.d.ts.map

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

export declare class TypeAssertion extends Error {
}
export declare const TypeAssertion: TypeErrorConstructor;
//# sourceMappingURL=TypeAssertion.d.ts.map
import type { Optional } from './Optional.type';
export declare type TypeCast<Output, Input = unknown> = (value: Input, fallback?: Output) => Output;
export interface TypeCast<Output, Input = unknown> {
(value: Input): Output;
(value: Input, fallback?: Output): Output;
}
export declare type OptionalTypeCast<Output, Input = unknown> = (value: Optional<Input>) => Output | undefined;
//# sourceMappingURL=TypeCast.type.d.ts.map

@@ -7,2 +7,5 @@ export interface TypeCheck<T> {

export declare type UnwrapTypeCheckArray<T extends TypeCheck<unknown>[]> = T extends TypeCheck<infer P>[] ? P : never;
export declare type UnwrapTypeCheckTuple<T extends TypeCheck<unknown>[]> = {
[Index in keyof T]: T[Index] extends TypeCheck<infer P> ? P : never;
};
//# sourceMappingURL=TypeCheck.type.d.ts.map
{
"name": "ts-runtime-typecheck",
"version": "2.5.0",
"version": "2.6.0",
"description": "A collection of common types for TypeScript along with dynamic type cast methods.",

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

"test": "jest --verbose --coverage",
"lint": "eslint",
"lint": "eslint src",
"typecheck": "tsc --noEmit --watch",
"build": "rollup -c && cp ./package.json ./dist/package.json && cp ./README.md ./dist/README.md"

@@ -21,12 +22,12 @@ },

"devDependencies": {
"@types/jest": "^27.4.0",
"@typescript-eslint/eslint-plugin": "^5.9.0",
"@typescript-eslint/parser": "^5.9.0",
"eslint": "^8.6.0",
"@types/jest": "^27.4.1",
"@typescript-eslint/eslint-plugin": "^5.17.0",
"@typescript-eslint/parser": "^5.17.0",
"eslint": "^8.12.0",
"jest": "^27.4.5",
"rollup": "^2.63.0",
"rollup-plugin-typescript2": "^0.31.1",
"ts-jest": "^27.1.2",
"typescript": "^4.5.4"
"rollup": "^2.70.1",
"rollup-plugin-typescript2": "^0.31.2",
"ts-jest": "^27.1.4",
"typescript": "^4.6.3"
}
}

@@ -25,3 +25,2 @@ # ts-runtime-typecheck

- [Type Casts](#type-casts)
- [Fallback values](#fallback-values)
- [Type Checks](#type-checks)

@@ -36,26 +35,5 @@ - [Type Coerce](#type-coerce)

- [Class instances](#class-instances)
- [Guarded functions](#guarded-functions)
- [Reference](#reference)
- [Reference: Type Casts](#reference-type-casts)
- [Reference: Optional Type Casts](#reference-optional-type-casts)
- [Reference: Type Checks](#reference-type-checks)
- [Reference: Optional Type Checks](#reference-optional-type-checks)
- [Reference: Type Coerce](#reference-type-coerce)
- [Reference: Type Assert](#reference-type-assert)
- [Reference: Helper functions](#reference-helper-functions)
- [Reference: Types](#reference-types)
- [Changelog](#changelog)
- [v1.0.0](#v100)
- [v1.1.0](#v110)
- [v1.1.1](#v111)
- [v1.2.0](#v120)
- [v2.0.0](#v200)
- [v2.1.0](#v210)
- [v2.1.1](#211)
- [v2.2.0](#220)
- [v2.2.1](#221)
- [v2.2.2](#222)
- [v2.3.0](#230)
- [v2.4.0](#240)
- [v2.5.0](#250)

@@ -84,24 +62,6 @@ ## Type Casts

### Fallback values
### Optional Type Casts
The standard type cast functions take a second optional parameter, which is a _fallback_ value. In the situation that the input is [`Nullish`](#nullish) and the fallback parameter has been defined the function will return the fallback parameter instead of throwing. This is very helpful for validating the input of an optional value, and providing a default value.
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 when a [`Nullish`](#nullish) value is passed in they will emit `undefined` instead of throwing. 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.
```typescript
import { asString } from 'ts-runtime-typecheck';
function printName (name: unknown) {
const value: string = asString(name, 'Dave');
console.log(`Hello ${value}, how are you today?`);
}
printName()
// Hello Dave, how are you today?
printName('James')
// Hello James, now are you today?
printName(42)
// Error: Unable to cast number to string
```
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.
---

@@ -190,3 +150,3 @@

TypeAsserts cannot be based on generic types, due to limits in the TypeScript type system. Hence there is no equivalent to [`isStruct`](#isstruct) and similar [`TypeCheck`](#typecheck). However, there is an alternative. It's possible to utilise an invariant ( or assert) function with a [`TypeCheck`](#typecheck) to get the same effect, and an implementation of [`invariant`](#invariant) is provided for this purpose.
TypeAsserts cannot be based on generic types, due to limits in the TypeScript type system. Hence there is no analogous function to [`isStruct`](#isstruct) and similar [`TypeCheck`](#typecheck). However, there is an alternative. It's possible to utilise an invariant ( or assert) function with a [`TypeCheck`](#typecheck) to get the same effect, and an implementation of [`invariant`](#invariant) is provided for this purpose.

@@ -269,16 +229,30 @@ ```typescript

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.
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. A safer alternative is to use [`asDefined`](#asdefined) and friends, which can be used to subtract the optionality from the type.
```typescript
import { asDefined } from 'ts-runtime-typecheck';
import { asDefined, assertDefined, isDefined } from 'ts-runtime-typecheck';
function setup (useComplexType: boolean = false, complexInst?: ComplexType) {
if (useComplexType) {
const inst: ComplexType = asDefined(complexInst);
inst.doComplexThing();
function doThing (value: number) {
// [...]
}
function branching (value?: number) {
// used for conditions, allows for an alternative to throwing or custom error behavior
if (isDefined(value)) {
doThing(value)
} else {
console.log('bad things')
}
else {
doSimpleThing();
}
}
function inline (value?: number) {
// used inline, throws if the value is Nullish otherwise returns the value
doThing(asDefined(value))
}
function assertion (value?: number) {
// used to ensure execution doesn't progress if the value isn't defined, throws if the value is Nullish
assertDefined(value)
doThing(value)
}
```

@@ -458,2 +432,21 @@

---
## Guarded Functions
TypeScript provides excellent compile time protections against misusing functions. The number of parameters, the types of parameters and the return type of the function are all statically type checked. But it provides no *runtime* protections. In a pure TS project this isn't normally required, but sometimes you need to pass around abstract functions and have them behave reliably. Alternatively you could be authoring a library and want to ensure that developers using your library without TS use your functions correctly. In both these scenarios you can wrap the function using `asGuardedFunction`, specifying the return and parameter types. This will return a new function that when called will validate the incoming arguments, and the outgoing return value at runtime. If the types don't match up it will throw an error. The resulting function will have accurate parameter and return types, irrespective of the original function.
```typescript
import { asGuardedFunction } from 'ts-runtime-typecheck';
export const publicFunction = asGuardedFunction(
(a: number, b: number) => `${(a / b) * 100}%`, // function to wrap
isString, // return value
isNumber, isNumber // parameters
);
```
---
## Reference

@@ -465,63 +458,63 @@

Cast `unknown` to `string`. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to `string`.
- ### asNumber
Cast `unknown` to `number`. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to `number`.
- ### asIndex
Cast `unknown` to [`Index`](#index). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`Index`](#index).
- ### asPrimitive
Cast `unknown` to [`Primitive`](#primitive). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`Primitive`](#primitive).
- ### asIndexable
Cast `unknown` to [`Indexable`](#indexable). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`Indexable`](#indexable).
- ### asBoolean
Cast `unknown` to `boolean`. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to `boolean`.
- ### asArray
Cast `unknown` to `Array<unknown>`. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to `Array<unknown>`.
- ### asDictionary
Cast `unknown` to [`Dictionary<unknown>`](#dictionary). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`Dictionary<unknown>`](#dictionary).
- ### asFunction
Cast `unknown` to [`UnknownFunction`](#unknownfunction). Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`UnknownFunction`](#unknownfunction).
- ### asDefined
Cast [`Type | Nullish`](#nullish) to `Type`, where `Type` is a generic parameter. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast [`Type | Nullish`](#nullish) to `Type`, where `Type` is a generic parameter.
- ### asJSONValue
Cast `unknown` to [`JSONValue`](#jsonvalue). This function recursively validates the value, and hence will fail if given a cyclic value. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast `unknown` to [`JSONValue`](#jsonvalue). This function recursively validates the value, and hence will fail if given a cyclic value.
- ### asJSONObject
Cast [`JSONValue`](#jsonvalue) to [`JSONObject`](#jsonobject). Unlike [`asJSONValue`](#asjsonvalue) this does not perform recursive validation, hence it only accepts a [`JSONValue`](#jsonvalue) so that the sub-elements are of a known type. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast [`JSONValue`](#jsonvalue) to [`JSONObject`](#jsonobject). Unlike [`asJSONValue`](#asjsonvalue) this does not perform recursive validation, hence it only accepts a [`JSONValue`](#jsonvalue) so that the sub-elements are of a known type.
- ### asJSONArray
Cast [`JSONValue`](#jsonvalue) to [`JSONArray`](#jsonarray). Unlike [`asJSONValue`](#asjsonvalue) this does not perform recursive validation, hence it only accepts a [`JSONValue`](#jsonvalue) so that the sub-elements are of a known type. Accepts an optional fallback value that is emitted if the value is nullish and fallback is defined.
Cast [`JSONValue`](#jsonvalue) to [`JSONArray`](#jsonarray). Unlike [`asJSONValue`](#asjsonvalue) this does not perform recursive validation, hence it only accepts a [`JSONValue`](#jsonvalue) so that the sub-elements are of a known type.
- ### 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 [Array/Object of Type Casts](#arrayobject-of-type-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. Refer to [Array/Object of Type Casts](#arrayobject-of-type-casts) for examples.
- ### 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 [Array/Object of Type Casts](#arrayobject-of-type-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. 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 [Validating interfaces](#validating-interfaces) 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 [`TypeChecks`](#typecheck) specified in the pattern. Refer to [Validating interfaces](#validating-interfaces) for examples.

@@ -536,2 +529,6 @@ - ### asInstance

- ### asGuardedFunction
Takes a unknown value and a series of [`TypeChecks`](#typecheck) and returns a strongly typed function. It will be a new function that wraps the original with runtime type validation, ensuring that the arguments and return value are the expected types. The first [`TypeCheck`](#typecheck) is for the return value, and subsequent variadic [`TypeChecks`](#typecheck) are used for validating arguments.
### Reference: Optional Type Casts

@@ -986,3 +983,3 @@

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.
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 [TypeChecks](#reference-type-checks) conform to this type.

@@ -1094,1 +1091,8 @@ - ### InterfacePattern

- Change: Type error messages now use the more descriptive `inspectType` instead of `typeof` for erroneous values
### 2.6.0
- Add: `asGuardedFunction` to wrap a function with parameter/return value type checks
- Change: Depreciate the fallback parameter for all TypeCasts
- Documentation: Simplify the contents into primary headings only
- Change: Instead of being a custom subclass of Error TypeAssertion is now an alias to TypeError

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

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

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

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

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

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

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

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

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