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.
Typeforce is a runtime type-checking library for JavaScript. It allows developers to enforce types and structures on their data, ensuring that the data conforms to expected formats. This can be particularly useful for validating function arguments, API responses, and more.
Basic Type Checking
Typeforce provides basic type checking for primitive types like strings, numbers, booleans, etc. The example demonstrates how to check if a value is a string.
const typeforce = require('typeforce');
// Define a type check for a string
const isString = typeforce.String;
// Validate a value
console.log(isString('Hello, World!')); // true
console.log(isString(123)); // throws an error
Custom Type Definitions
Typeforce allows you to define custom type checks using functions. The example shows how to create a custom type check for even numbers.
const typeforce = require('typeforce');
// Define a custom type check
const isEvenNumber = typeforce(function(value) {
return typeof value === 'number' && value % 2 === 0;
});
// Validate a value
console.log(isEvenNumber(4)); // true
console.log(isEvenNumber(5)); // throws an error
Object Structure Validation
Typeforce can validate the structure of objects, ensuring that they have the expected properties with the correct types. The example demonstrates how to validate an object representing a person.
const typeforce = require('typeforce');
// Define a type check for an object structure
const personType = {
name: typeforce.String,
age: typeforce.Number
};
// Validate an object
const person = { name: 'Alice', age: 30 };
console.log(typeforce(personType, person)); // true
const invalidPerson = { name: 'Bob', age: 'thirty' };
console.log(typeforce(personType, invalidPerson)); // throws an error
Array Type Checking
Typeforce can validate arrays, ensuring that all elements conform to a specified type. The example shows how to check if an array contains only numbers.
const typeforce = require('typeforce');
// Define a type check for an array of numbers
const isArrayofNumbers = typeforce(typeforce.ArrayOf(typeforce.Number));
// Validate an array
console.log(isArrayofNumbers([1, 2, 3])); // true
console.log(isArrayofNumbers([1, '2', 3])); // throws an error
Joi is a powerful schema description language and data validator for JavaScript. It allows you to create blueprints or schemas for JavaScript objects to ensure validation of key information. Compared to Typeforce, Joi offers a more extensive and flexible API for defining complex validation rules and is widely used in the Node.js community.
Yup is a JavaScript schema builder for value parsing and validation. It is similar to Joi but is often preferred for its simplicity and ease of use, especially in React applications. Yup provides a fluent API for object schema validation and is highly customizable.
Prop-types is a runtime type-checking library for React props. It allows you to specify the types of props that a component should receive, providing warnings in development mode if the props do not match the specified types. While it is more specialized for React, it offers similar type-checking capabilities as Typeforce.
Another biased type checking solution for Javascript.
Exception messages may change between patch versions, as often the patch will change some behaviour that was unexpected and naturally it results in a different error message.
var typeforce = require('typeforce')
var element = { prop: 'foo' }
var elementNumber = { prop: 2 }
var array = [element, element, elementNumber]
// supported primitives 'Array', 'Boolean', 'Buffer', 'Number', 'Object', 'String'
typeforce('Array', array)
typeforce('Number', array)
// TypeError: Expected Number, got Array
// array types
typeforce(['Object'], array)
typeforce(typeforce.arrayOf('Object'), array)
// supports recursive type templating
typeforce({ prop: 'Number' }, elementNumber)
// maybe types
typeforce('?Number', 2)
typeforce('?Number', null)
typeforce(typeforce.maybe(typeforce.Number), 2)
typeforce(typeforce.maybe(typeforce.Number), null)
// sum types
typeforce(typeforce.anyOf('String', 'Number'), 2)
typeforce(typeforce.allOf({ x: typeforce.Number }, { y: typeforce.Number }), {
x: 1,
y: 2
})
// value types
typeforce(typeforce.value(3.14), 3.14)
// custom types
function LongString (value, strict) {
if (!typeforce.String(value)) return false
if (value.length !== 32) return false
return true
}
typeforce(LongString, '00000000000000000000000000000000')
// => OK!
typeforce(LongString, 'not long enough')
// TypeError: Expected LongString, got String 'not long enough'
Protips:
// use precompiled primitives for high performance
typeforce(typeforce.Array, array)
// or just precompile a template
var type = {
foo: 'Number',
bar: '?String'
}
var fastType = typeforce.compile(type)
// fastType => typeforce.object({
// foo: typeforce.Number,
// bar: typeforce.maybe(typeforce.String)
// })
// use strictness for recursive types to enforce whitelisting properties
typeforce({
x: 'Number'
}, { x: 1 }, true)
// OK!
typeforce({
x: 'Number'
}, { x: 1, y: 2 }, true)
// TypeError: Unexpected property 'y' of type Number
Protips (extended types):
typeforce(typeforce.tuple('String', 'Number'), ['foo', 1])
// OK!
typeforce(typeforce.tuple('Number', 'Number'), ['not a number', 1])
// TypeError: Expected property "0" of type Number, got String 'not a number'
typeforce(typeforce.map('Number'), {
'anyKeyIsOK': 1
})
// OK!
typeforce(typeforce.map('Number', typeforce.HexN(8)), {
'deadbeef': 1,
'ffff0000': 2
})
// OK!
function Foo () {
this.x = 2
}
typeforce(typeforce.quacksLike('Foo'), new Foo())
// OK!
// Note, any Foo will do
typeforce(typeforce.quacksLike('Foo'), new (function Foo() {}))
// OK!
Protips (no throw)
var typeforce = require('typeforce/nothrow')
var value = 'foobar'
if (typeforce(typeforce.Number, value)) {
// didn't throw!
console.log(`${value} is a number`) // never happens
} else {
console.log(`Oops, ${typeforce.error.message}`)
// prints 'Oops, Expected Number, got String foobar'
}
Protips (async)
var typeforce = require('typeforce/async')
typeforce(typeforce.Number, value, function (err) {
if (err) return console.log(`Oops, ${typeforce.error.message}`)
console.log(`${value} is a number`) // never happens
})
WARNING: Be very wary of using the quacksLike
type, as it relies on the Foo.name
property.
If that property is mangled by a transpiler, such as uglifyjs
, you will have a bad time.
FAQs
Another biased type checking solution for Javascript
The npm package typeforce receives a total of 163,505 weekly downloads. As such, typeforce popularity was classified as popular.
We found that typeforce 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.