Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
type-check allows you to check the types of JavaScript values at runtime with a Haskell like type syntax.
The type-check npm package allows you to check the types of JavaScript values at runtime with a simple and readable syntax. It is useful for validating function arguments, ensuring data integrity, and preventing type-related bugs.
Basic type checking
This feature allows you to check if a value matches a basic type, such as 'String', 'Number', 'Boolean', etc.
const { typeCheck } = require('type-check');
typeCheck('String', 'a string'); // returns true
Complex type checking
This feature enables checking against more complex types, such as objects with specific properties and types.
const { typeCheck } = require('type-check');
typeCheck('{name: String, age: Number}', {name: 'Alice', age: 30}); // returns true
Custom type definitions
With this feature, you can define custom types and then check values against those custom types.
const { typeCheck, define } = require('type-check');
define('Person', '{name: String, age: Number}');
typeCheck('Person', {name: 'Bob', age: 25}); // returns true
Array type checking
This feature allows you to check if an array contains values of a specific type.
const { typeCheck } = require('type-check');
typeCheck('[Number]', [1, 2, 3]); // returns true
Prop-types is a library for runtime type checking for React props and similar objects. It is often used in React applications to ensure that components receive props of the correct type. It is more specific to React, whereas type-check is more general-purpose.
Joi is a powerful schema description language and data validator for JavaScript. It allows for detailed object schema validation and is often used for validating complex data structures, making it more feature-rich compared to type-check.
Ajv is a JSON schema validator. It validates data against JSON Schema standards and is known for its performance and support for the latest JSON Schema features. It is more suited for JSON data validation and is more comprehensive than type-check.
typescript-is is a TypeScript library that provides runtime type checking for TypeScript interfaces. It leverages the TypeScript compiler to generate runtime checks, making it a good choice for TypeScript projects, unlike type-check which is not TypeScript-specific.
type-check
is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of levn. MIT license. Version 0.4.0. Check out the demo.
For updates on type-check
, follow me on twitter.
npm install type-check
// Basic types:
var typeCheck = require('type-check').typeCheck;
typeCheck('Number', 1); // true
typeCheck('Number', 'str'); // false
typeCheck('Error', new Error); // true
typeCheck('Undefined', undefined); // true
// Comment
typeCheck('count::Number', 1); // true
// One type OR another type:
typeCheck('Number | String', 2); // true
typeCheck('Number | String', 'str'); // true
// Wildcard, matches all types:
typeCheck('*', 2) // true
// Array, all elements of a single type:
typeCheck('[Number]', [1, 2, 3]); // true
typeCheck('[Number]', [1, 'str', 3]); // false
// Tuples, or fixed length arrays with elements of different types:
typeCheck('(String, Number)', ['str', 2]); // true
typeCheck('(String, Number)', ['str']); // false
typeCheck('(String, Number)', ['str', 2, 5]); // false
// Object properties:
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2}); // false
typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true
typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false
typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true
// A particular type AND object properties:
typeCheck('RegExp{source: String, ...}', /re/i); // true
typeCheck('RegExp{source: String, ...}', {source: 're'}); // false
// Custom types:
var opt = {customTypes:
{Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}};
typeCheck('Even', 2, opt); // true
// Nested:
var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}'
typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true
Check out the type syntax format and guide.
require('type-check');
returns an object that exposes four properties. VERSION
is the current version of the library as a string. typeCheck
, parseType
, and parsedTypeCheck
are functions.
// typeCheck(type, input, options);
typeCheck('Number', 2); // true
// parseType(type);
var parsedType = parseType('Number'); // object
// parsedTypeCheck(parsedType, input, options);
parsedTypeCheck(parsedType, 2); // true
typeCheck
checks a JavaScript value input
against type
written in the type format (and taking account the optional options
) and returns whether the input
matches the type
.
String
- the type written in the type format which to check against*
- any JavaScript value, which is to be checked against the typeMaybe Object
- an optional parameter specifying additional options, currently the only available option is specifying custom typesBoolean
- whether the input matches the type
typeCheck('Number', 2); // true
parseType
parses string type
written in the type format into an object representing the parsed type.
String
- the type written in the type format which to parseObject
- an object in the parsed type format representing the parsed type
parseType('Number'); // [{type: 'Number'}]
parsedTypeCheck
checks a JavaScript value input
against parsed type
in the parsed type format (and taking account the optional options
) and returns whether the input
matches the type
. Use this in conjunction with parseType
if you are going to use a type more than once.
Object
- the type in the parsed type format which to check against*
- any JavaScript value, which is to be checked against the typeMaybe Object
- an optional parameter specifying additional options, currently the only available option is specifying custom typesBoolean
- whether the input matches the type
parsedTypeCheck([{type: 'Number'}], 2); // true
var parsedType = parseType('String');
parsedTypeCheck(parsedType, 'str'); // true
## Type Format
White space is ignored. The root node is a Types.
[\$\w]+
- a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. String
Identifier
, an Identifier
followed by a Structure
, just a Structure
, or a wildcard *
- eg. String
, Object{x: Number}
, {x: Number}
, Array{0: String, 1: Boolean, length: Number}
, *
Identifier
followed by a ::
), optionally the identifier Maybe
, one or more Type
, separated by |
- eg. Number
, String | Date
, Maybe Number
, Maybe Boolean | String
Fields
, or a Tuple
, or an Array
- eg. {x: Number}
, (String, Number)
, [Date]
{
, followed one or more Field
separated by a comma ,
(trailing comma ,
is permitted), optionally an ...
(always preceded by a comma ,
), followed by a }
- eg. {x: Number, y: String}
, {k: Function, ...}
Identifier
, followed by a colon :
, followed by Types
- eg. x: Date | String
, y: Boolean
(
, followed by one or more Types
separated by a comma ,
(trailing comma ,
is permitted), followed by a )
- eg (Date)
, (Number, Date)
[
followed by exactly one Types
followed by a ]
- eg. [Boolean]
, [Boolean | Null]
type-check
uses Object.toString
to find out the basic type of a value. Specifically,
{}.toString.call(VALUE).slice(8, -1)
{}.toString.call(true).slice(8, -1) // 'Boolean'
A basic type, eg. Number
, uses this check. This is much more versatile than using typeof
- for example, with document
, typeof
produces 'object'
which isn't that useful, and our technique produces 'HTMLDocument'
.
You may check for multiple types by separating types with a |
. The checker proceeds from left to right, and passes if the value is any of the types - eg. String | Boolean
first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false.
Adding a Maybe
in front of a list of multiple types is the same as also checking for Null
and Undefined
- eg. Maybe String
is equivalent to Undefined | Null | String
.
You may add a comment to remind you of what the type is for by following an identifier with a ::
before a type (or multiple types). The comment is simply thrown out.
The wildcard *
matches all types.
There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'.
If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of Object
and the properties pass - this allows for duck typing - eg. {x: Boolean}
.
To check if the properties pass, and the value is of a certain type, you can specify the type - eg. Error{message: String}
.
If you want to make a field optional, you can simply use Maybe
- eg. {x: Boolean, y: Maybe String}
will still pass if y
is undefined (or null).
If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator ...
- eg. {x: Boolean, ...}
will match an object with an x
property that is a boolean, and with zero or more other properties.
For an array, you must specify one or more types (separated by |
) - it will pass for something of any length as long as each element passes the types provided - eg. [Number]
, [Number | String]
.
A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. (String, Number)
.
An array and tuple structure check that the value is of type Array
by default, but if another type is specified, they will check for that instead - eg. Int32Array[Number]
. You can use the wildcard *
to search for any type at all.
Check out the type precedence library for type-check.
Options is an object. It is an optional parameter to the typeCheck
and parsedTypeCheck
functions. The only current option is customTypes
.
Example:
var options = {
customTypes: {
Even: {
typeOf: 'Number',
validate: function(x) {
return x % 2 === 0;
}
}
}
};
typeCheck('Even', 2, options); // true
typeCheck('Even', 3, options); // false
customTypes
allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a typeOf
property - a string, and validate
property - a function.
The typeOf
property is the type the value should be (optional - if not set only validate
will be used), and validate
is a function which should return true if the value is of that type. validate
receives one parameter, which is the value that we are checking.
type-check
is written in LiveScript - a language that compiles to JavaScript. It also uses the prelude.ls library.
FAQs
type-check allows you to check the types of JavaScript values at runtime with a Haskell like type syntax.
The npm package type-check receives a total of 28,655,871 weekly downloads. As such, type-check popularity was classified as popular.
We found that type-check demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.