Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/EnixCoda/safe-touch
⛓ Runtime optional chaining for JS
https://github.com/EnixCoda/safe-touch
javascript-library typescript-library
Last synced: 3 months ago
JSON representation
⛓ Runtime optional chaining for JS
- Host: GitHub
- URL: https://github.com/EnixCoda/safe-touch
- Owner: EnixCoda
- Created: 2018-07-11T08:19:04.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2021-08-19T17:23:20.000Z (about 3 years ago)
- Last Synced: 2024-07-31T05:42:29.238Z (3 months ago)
- Topics: javascript-library, typescript-library
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/safe-touch
- Size: 49.8 KB
- Stars: 73
- Watchers: 4
- Forks: 3
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
- my-awesome - EnixCoda / safe-touch - Touch deeply buried property safely with ease. (Library)
README
# Safe Touch
Retrieving deeply buried properties is a common problem in JavaScript, it could crash your application if you try to access a property that doesn't exist.
```js
const state = { user: { name: "EnixCoda" } };
console.log(state.user.name); // 'EnixCoda'
state.user = null; // simulating logout
console.log(state.user.name); // Uncaught TypeError: Cannot read property 'name' of null
```Safe touch is a safe way to access deeply buried properties.
```js
const $state = safeTouch(state); // retrieving properties from $state is always safe
console.log($state() === state); // true; invoke to get the original value
{
let { user: { name } } = $state; // support native destructuring
console.log(name()); // 'EnixCoda'
console.log($state.user.name()); // 'EnixCoda'
}Object.assign(state, { user: null }) // simulating logout
{
let { user: { name } } = $state; // support native destructuring
console.log(name()); // undefined; no errors!
console.log($state.user.name()); // undefined; no errors!
}
```[Playground](https://codesandbox.io/s/safe-touch-playground-o96vi)
Available as `safe-touch` on [npm](https://www.npmjs.com/package/safe-touch).
```shell
> yarn add safe-touch
```## Why choose Safe Touch?
- `state && state.user && state.user.name` is verbose.
- wrapping with `try ... catch` is verbose and creates new code block.
- lodash [`_.get`](https://lodash.com/docs/#get) has no TypeScript support.