https://github.com/amilajack/safe-access-check
A micro library that prevents unsafe coercion and property access in javascript
https://github.com/amilajack/safe-access-check
check coercion javascript safe
Last synced: 4 months ago
JSON representation
A micro library that prevents unsafe coercion and property access in javascript
- Host: GitHub
- URL: https://github.com/amilajack/safe-access-check
- Owner: amilajack
- Created: 2017-03-17T02:17:04.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-10-03T19:48:26.000Z (about 7 years ago)
- Last Synced: 2025-06-03T00:34:42.978Z (4 months ago)
- Topics: check, coercion, javascript, safe
- Language: JavaScript
- Homepage:
- Size: 83 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 5
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
safe-access-check
=========
[](https://travis-ci.org/amilajack/safe-access-check)
[](http://badge.fury.io/js/safe-access-check)
[](https://david-dm.org/amilajack/safe-access-check)
[](https://npm-stat.com/charts.html?package=safe-access-check)**⚠️ Experimental. Intended to be used by compilers and code checkers ⚠️**
## Todos
- [ ] Existential check of enumerable properties
- [ ] Optional logging of values recieved
- [ ] Clearer, more consistent error messages## Installation
```bash
npm install --save-dev safe-access-check
```## Usage
```js
import { safeCoerce, safePropertyAccess } from 'safe-access-check';// ------------------------------------------------
// 1. Usage as an expression
// ------------------------------------------------
let some = moo + '10' // 'moo10'
some = safeCoerce('moo', '+', 10) // 'moo10'// ------------------------------------------------
// 2. Usage for coercion safeguard
// ------------------------------------------------
[] + {} // "[object Object]"safeCoerce([], '+', {})
// TypeError: 'Unexpected coercion of type "Object" and
// type "Array" using "+" operator'NaN + undefined // NaN
safeCoerce(NaN, '+', undefined);
// TypeError: Unexpected coercion of type "NaN" and type
// "undefined" using "+" operatorsafeCoerce(new String('12'), '>', 12);
// TypeError: Unexpected comparison of type "String" and type
// "number" using ">" operator// ------------------------------------------------
// 3. Usage for better undefined propagation errors
// ------------------------------------------------
const obj = {
foo: {
bar: {
baz: false
}
}
}obj.foo.bar._MOO_.baz;
// TypeError: 'Cannot read property 'baz' of undefined'safePropertyAccess(['foo', 'bar', '_MOO_', 'baz'], obj);
// TypeError: Property "_MOO_" does not exist in "Object.foo._MOO_"// ------------------------------------------------
// 4. Usage as out of bounds check
// ------------------------------------------------
const obj = {
woo: ['']
}obj.woo[1] // undefined
safePropertyAccess(['woo', 1], obj)
// TypeError: '"woo[1]" is out of bounds'
```