type-check
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|---|---|---|---|---|
prelude-ls | 1.2.1 | 9.19 kB | MIT | prod |
Type-check is a powerful JavaScript library extensively employed for checking the types of JavaScript values dynamically. It uses a Haskell-like type syntax and serves as a vital component of levn. The type-check library is ideal for verifying external input, adding extra protection to your internal code, and performing testing. Primarily, type-check is practical to use when you want to check the type at runtime. It supports type validations such as basic types (Number
, Boolean
, Undefined
etc.), composite types (Tuples, Objects and Arrays) and also allows for custom types.
To use type-check, start by installing it via npm with the command npm install type-check
. The package provides a typeCheck
function that you can use to check if a value matches a specific type.
Here are some code examples demonstrating its usage:
var typeCheck = require('type-check').typeCheck;
// Basic types:
console.log(typeCheck('Number', 1)); // true
console.log(typeCheck('Error', new Error)); // true
// Comment
console.log(typeCheck('count::Number', 1)); // true
// One type OR another type:
console.log(typeCheck('Number | String', 2)); // true
// Wildcard, matches all types:
console.log(typeCheck('*', 2)) // true
// Array, all elements of a single type:
console.log(typeCheck('[Number]', [1, 2, 3])); // true
// Tuples, or fixed-length arrays with elements of different types:
console.log(typeCheck('(String, Number)', ['str', 2])); // true
// Object properties:
console.log(typeCheck('{x: Number, y: Boolean}', {x: 2, y: false})); // true
// A particular type AND object properties:
console.log(typeCheck('RegExp{source: String, ...}', /re/i)); // true
// Custom types:
var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}};
console.log(typeCheck('Even', 2, opt)); // true
It's worth noting that type-check also provides parseType
and parsedTypeCheck
functions. parseType
creates an object representing the parsed type from a string type and parsedTypeCheck
checks whether an input matches the parsed type.
The documentation for the type-check library, which includes details about its type syntax format and guide, can be found in its readme file on the GitHub repository URL. The readme provides a comprehensive guide on how to use this library, complete with examples and detailed explanations of various scenarios. It also includes information on the different types that can be checked, how to create custom types, and how to use the library's different functions effectively. As such, it's your one-stop location for all type-check related information.