Research
Security News
Malicious npm Package Targets Solana Developers and Hijacks Funds
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
typed-function
Advanced tools
The typed-function npm package allows you to define functions with typed arguments in JavaScript. It provides a way to enforce type checking at runtime, making your code more robust and easier to debug.
Define a typed function
This feature allows you to define a function with multiple signatures, each with different types of arguments. The function will execute the appropriate implementation based on the types of the provided arguments.
const typed = require('typed-function');
const add = typed({
'number, number': function (a, b) {
return a + b;
},
'string, string': function (a, b) {
return a + b;
}
});
console.log(add(2, 3)); // 5
console.log(add('Hello, ', 'world!')); // 'Hello, world!'
Type checking
This feature enforces type checking at runtime, throwing an error if the provided arguments do not match any of the defined signatures. This helps catch type-related bugs early in the development process.
const typed = require('typed-function');
const multiply = typed({
'number, number': function (a, b) {
return a * b;
}
});
try {
console.log(multiply(2, '3')); // Throws an error
} catch (err) {
console.error(err.message); // 'TypeError: Unexpected type of argument in function multiply (expected: number, actual: string, index: 1)'
}
Default types
This feature allows you to define default types for your function arguments. If no arguments are provided or if they do not match any specific type, the function will fall back to the default implementation.
const typed = require('typed-function');
const greet = typed({
'string': function (name) {
return 'Hello, ' + name + '!';
},
'any': function () {
return 'Hello, world!';
}
});
console.log(greet('Alice')); // 'Hello, Alice!'
console.log(greet()); // 'Hello, world!'
io-ts is a runtime type system for IO decoding/encoding in TypeScript. It allows you to define types and validate data at runtime. Compared to typed-function, io-ts is more focused on data validation and transformation rather than function overloading.
Runtypes provides a way to define and validate types at runtime in TypeScript. It offers a similar type-checking functionality but is more geared towards defining and validating data structures rather than function signatures.
ts-runtime is a TypeScript transformer that adds runtime type checks to your TypeScript code. It provides a more integrated approach to type checking in TypeScript, whereas typed-function is a standalone library for JavaScript.
Move type checking logic and type conversions outside of your function in a flexible, organized way. Automatically throw informative errors in case of wrong input arguments.
typed-function has the following features:
Supported environments: node.js, Chrome, Firefox, Safari, Opera, IE11+.
In JavaScript, functions can be called with any number and any type of arguments. When writing a function, the easiest way is to just assume that the function will be called with the correct input. This leaves the function's behavior on invalid input undefined. The function may throw some error, or worse, it may silently fail or return wrong results. Typical errors are TypeError: undefined is not a function or TypeError: Cannot call method 'request' of undefined. These error messages are not very helpful. It can be hard to debug them, as they can be the result of a series of nested function calls manipulating and propagating invalid or incomplete data.
Often, JavaScript developers add some basic type checking where it is important,
using checks like typeof fn === 'function'
, date instanceof Date
, and
Array.isArray(arr)
. For functions supporting multiple signatures,
the type checking logic can grow quite a bit, and distract from the actual
logic of the function.
For functions dealing with a considerable amount of type checking and conversion
logic, or functions facing a public API, it can be very useful to use the
typed-function
module to handle the type-checking logic. This way:
It's important however not to overuse type checking:
Install via npm:
npm install typed-function
Here some usage examples. More examples are available in the /examples folder.
var typed = require('typed-function');
// create a typed function
var fn1 = typed({
'number, string': function (a, b) {
return 'a is a number, b is a string';
}
});
// create a typed function with multiple types per argument (type union)
var fn2 = typed({
'string, number | boolean': function (a, b) {
return 'a is a string, b is a number or a boolean';
}
});
// create a typed function with any type argument
var fn3 = typed({
'string, any': function (a, b) {
return 'a is a string, b can be anything';
}
});
// create a typed function with multiple signatures
var fn4 = typed({
'number': function (a) {
return 'a is a number';
},
'number, boolean': function (a, b) {
return 'a is a number, b is a boolean';
},
'number, number': function (a, b) {
return 'a is a number, b is a number';
}
});
// create a typed function from a plain function with signature
function fnPlain(a, b) {
return 'a is a number, b is a string';
}
fnPlain.signature = 'number, string';
var fn5 = typed(fnPlain);
// use the functions
console.log(fn1(2, 'foo')); // outputs 'a is a number, b is a string'
console.log(fn4(2)); // outputs 'a is a number'
// calling the function with a non-supported type signature will throw an error
try {
fn2('hello', 'world');
}
catch (err) {
console.log(err.toString());
// outputs: TypeError: Unexpected type of argument.
// Expected: number or boolean, actual: string, index: 1.
}
typed-function has the following built-in types:
null
boolean
number
string
Function
Array
Date
RegExp
Object
The following type expressions are supported:
string, number, Function
number | string
...number
any
A typed function can be constructed in two ways:
Create from an object with one or multiple signatures:
typed(signatures: Object.<string, function>) : function
typed(name: string, signatures: Object.<string, function>) : function
Merge multiple typed functions into a new typed function:
typed(functions: ...function) : function
typed(name: string, functions: ...function) : function
Each function in functions
can be either a typed function created before,
or a plain function having a signature
property.
typed.convert(value: *, type: string) : *
Convert an value to another type. Only applicable when conversions have
been defined in typed.conversions
(see section Properties).
Example:
typed.conversions.push({
from: 'number',
to: 'string',
convert: function (x) {
return +x;
});
var str = typed.convert(2.3, 'string'); // '2.3'
typed.create() : function
Create a new, isolated instance of typed-function. Example:
var typed = require('typed-function'); // default instance
var typed2 = typed.create(); // a second instance
typed.find(fn: function, signature: string | Array) : function | null
Find a specific signature from a typed function. The function currently only finds exact matching signatures.
For example:
var fn = typed(...);
var f = typed.find(fn, ['number', 'string']);
var f = typed.find(fn, 'number, string');
typed.addType(type: {name: string, test: function} [, beforeObjectTest=true])
Add a new type. A type object contains a name and a test function.
The order of the types determines in which order function arguments are
type-checked, so for performance it's important to put the most used types
first. All types are added to the Array typed.types
.
Example:
function Person(...) {
...
}
Person.prototype.isPerson = true;
typed.addType({
name: 'Person',
test: function (x) {
return x && x.isPerson === true;
}
});
By default, the new type will be inserted before the Object
test
because the Object
test also matches arrays and classes and hence
typed-function
would never reach the new type. When beforeObjectTest
is false
, the new type will be added at the end of all tests.
typed.addConversion(conversion: {from: string, to: string, convert: function}
Add a new conversion. Conversions are added to the Array typed.conversions
.
typed.addConversion({
from: 'boolean',
to: 'number',
convert: function (x) {
return +x;
});
typed.types: Array.<{name: string, test: function}>
Array with types. Each object contains a type name and a test function. The order of the types determines in which order function arguments are type-checked, so for performance it's important to put the most used types first. Custom types can be added like:
function Person(...) {
...
}
Person.prototype.isPerson = true;
typed.types.push({
name: 'Person',
test: function (x) {
return x && x.isPerson === true;
}
});
typed.conversions: Array.<{from: string, to: string, convert: function}>
An Array with built-in conversions. Empty by default. Can be used for example
to defined conversions from boolean
to number
. For example:
typed.conversions.push({
from: 'boolean',
to: 'number',
convert: function (x) {
return +x;
});
typed.ignore: Array.<string>
An Array with names of types to be ignored when creating a typed function. This can be useful filter signatures when creating a typed function. Example:
// a set with signatures maybe loaded from somewhere
var signatures = {
'number': function () {...},
'string': function () {...}
}
// we want to ignore a specific type
typed.ignore = ['string'];
// the created function fn will only contain the 'number' signature
var fn = typed('fn', signatures);
The functions generated with typed({...})
have:
toString
. Returns well readable code which can be used to see
what the function exactly does. Mostly for debugging purposes.signatures
, which holds a map with the (normalized)
signatures as key and the original sub-functions as value.name
containing name of the typed function or an empty string.'[number], array'
or like number=, array
'?Object'
fallible
or optional
?'"linear" | "cubic"'
, '0..10'
, etc.'{name: string, age: number}'
'Object.<string, Person>'
'Array.<Person>'
To test the library, run:
npm test
To generate the minified version of the library, run:
npm run minify
2018-07-28, version 1.1.0
signature
.FAQs
Type checking for JavaScript functions
The npm package typed-function receives a total of 926,793 weekly downloads. As such, typed-function popularity was classified as popular.
We found that typed-function demonstrated a healthy version release cadence and project activity because the last version was released less than 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
A malicious npm package targets Solana developers, rerouting funds in 2% of transactions to a hardcoded address.
Security News
Research
Socket researchers have discovered malicious npm packages targeting crypto developers, stealing credentials and wallet data using spyware delivered through typosquats of popular cryptographic libraries.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.