Sarcastic
Cast unknown values to typed values
- Asserts that a value matches the defined type
- Returns a typed value
- Copies the value for type safety
Install
yarn add sarcastic
Usage
const is = ; const PKG_SHAPE = isshape name: isstring version: isstring private: is scripts: is bin: is; let pkg = ;// {// name: "sarcastic",// version: "1.0.0",// private: false,// scripts: { "test": "ava" },// bin: null// }
With strict typing:
; const PKG_SHAPE = isshape name: isstring version: isstring private: is scripts: is bin: is; type PkgShape = AssertionType<typeof PKG_SHAPE>; : PkgShape { return ;} let pkg = ;
API
is(val, assertion, name?)
;
You can optionally pass a name for the value so that errors are more descriptive:
;// example.pathTo.nestedKeys.withIndexesLike[14]
Alternatively you can pass a formatter as the name which will receive the path to the error as strings for keys and numbers for indexes:
;// example > pathTo > nestedKeys > withIndexesLike > 14
is.boolean
; // returns true; // returns false; // throws instanceof is.AssertionError
is.number
; // returns 42; // returns NaN; // throws instanceof is.AssertionError
is.string
; // returns ""; // returns "hi"; // throws instanceof is.AssertionError
is.array
; // returns []; // returns [1, 2, 3]; // throws instanceof is.AssertionError
is.func
; // returns () => {}; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.object
; // returns {}; // returns { foo: true }; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.arrayOf(assertion)
; // returns []; // returns [1, 2, 3]; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.arrayish(assertion)
; // returns [1]; // returns []; // returns [1, 2, 3]; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.objectOf(assertion)
; // returns {}; // returns { foo: true }; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.shape({ [key: string]: assertion })
let myShape = isshape foo: isboolean ; ; // returns { foo: true; // returns { foo: true }; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError; // throws instanceof is.AssertionError
is.maybe(assertion)
; // returns null; // returns null; // returns true; // throws instanceof is.AssertionError
is.default(assertion, defaultValue)
; // returns 42; // returns 42; // returns 3.14; // throws instanceof is.AssertionError
is.either(assertionA, assertionB)
; // returns true; // returns "hi"; // throws instanceof is.AssertionError
is.AssertionError
try ; catch err if err instanceof isAssertionError // an assertion error else // some other unexpected error