What is typeforce?
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.
What are typeforce's main functionalities?
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
Other packages similar to typeforce
joi
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
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
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.
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.
Examples
var typeforce = require('typeforce')
var element = { prop: 'foo' }
var elementNumber = { prop: 2 }
var array = [element, element, elementNumber]
typeforce('Array', array)
typeforce('Number', array)
typeforce(['Object'], array)
typeforce(typeforce.arrayOf('Object'), array)
typeforce({ prop: 'Number' }, elementNumber)
typeforce('?Number', 2)
typeforce('?Number', null)
typeforce(typeforce.maybe(typeforce.Number), 2)
typeforce(typeforce.maybe(typeforce.Number), null)
typeforce(typeforce.oneOf('String', 'Number'))
typeforce(typeforce.value(3.14), 3.14)
function LongString (value, strict) {
if (!typeforce.String(value)) return false
if (value.length !== 32) return false
return true
}
typeforce(LongString, '00000000000000000000000000000000')
typeforce(LongString, 'not long enough')
Protips:
typeforce(typeforce.Array, array)
var type = {
foo: 'Number',
bar: '?String'
}
var fastType = typeforce.compile(type)
typeforce({
x: 'Number'
}, { x: 1 }, true)
typeforce({
x: 'Number'
}, { x: 1, y: 2 }, true)
Protips (extended types):
typeforce(typeforce.tuple('String', 'Number'), ['foo', 1])
typeforce(typeforce.tuple('Number', 'Number'), ['not a number', 1])
typeforce(typeforce.map('Number'), {
'anyKeyIsOK': 1
})
typeforce(typeforce.map('Number', typeforce.HexN(8)), {
'deadbeef': 1,
'ffff0000': 2
})
function Foo () {
this.x = 2
}
typeforce(typeforce.quacksLike('Foo'), new Foo())
typeforce(typeforce.quacksLike('Foo'), new (function Foo() {}))
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.
LICENSE MIT