Security News
Supply Chain Attack Detected in @solana/web3.js Library
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
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.
Type checking for JavaScript functions.
Features:
Supported environments: node.js, Chrome, Firefox, Safari, Opera, IE9+.
Install via npm:
npm install typed-function
Example usage:
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';
}
});
// 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 {
fn4('hello world');
}
catch (err) {
console.log(err.toString());
// outputs: TypeError: Unexpected type of argument.
// Expected: number, actual: string, index: 0.
}
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 as:
typed(signature: string, fn: function) : function
typed(name: string, signature: string, fn: function) : function
typed(signatures: Object.<string, function>) : function
typed(name: string, signatures: Object.<string, function>) : function
typed.types: Object
A map with the object types as key and a type checking test as value. Custom types can be added like:
function Person(...) {
...
}
typed.types['Person'] = function (x) {
return x instanceof Person;
};
- `typed.conversions: Array`
An Array with built-in conversions. Empty by default. Can be used for example
to defined conversions from `boolean` to `number`. For example:
```js
typed.conversions.push({
from: 'boolean',
to: 'number',
convert: function (x) {
return +x;
});
```
- `typed.config: Object`
An object with configuration options for typed-function:
- `minify: boolean`
If true (default), the functions are generated from minified code.
If false the typed-functions have a nicely readable .toString() source.
### Output
The functions generated with `typed({...})` have:
- A function `toString`. When `typed.config.minify` is set to `true` (is `false`
by default), the `toString` function will return well readable code which can
be used to see what the function exactly does. For debugging purposes.
- A property `signatures`, which holds a map with the (normalized)
signatures as key and the original sub-functions as value.
## Performance
Type checking input arguments adds some overhead to a function. For very small
functions this overhead can be larger than the function execution itself is,
but for any non-trivial function the overhead is typically small to neglectable.
You need to keep in mind though that you probably would have to do the type
checking done by `typed-function` anyway.
## Roadmap
### Version 1
- Extend function signatures:
- Optional arguments like `'[number], array'` or like `number=, array`
- Nullable arguments like `'?Object'`
- Be able to merge typed functions into a new typed function, like
`fn1 = merged(fn2, fn3)`.
- Create a good benchmark, to get insight in the overhead.
- Allow conversions not to be able to convert any input (for example string to
number is not always possible).
### Version 2
- Extend function signatures:
- Constants like `'"linear" | "cubic"'`, `'0..10'`, etc.
- Object definitions like `'{name: string, age: number}'`
- Object definitions like `'Object.<string, Person>'`
- Array definitions like `'Array.<Person>'`
## Test
To test the library, run:
npm test
## Minify
To generate the minified version of the library, run:
npm run minify
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.
Security News
A supply chain attack has been detected in versions 1.95.6 and 1.95.7 of the popular @solana/web3.js library.
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.