https://github.com/0x80/get-or-throw
A convenience function for safely getting values from dynamic objects and arrays
https://github.com/0x80/get-or-throw
Last synced: about 8 hours ago
JSON representation
A convenience function for safely getting values from dynamic objects and arrays
- Host: GitHub
- URL: https://github.com/0x80/get-or-throw
- Owner: 0x80
- License: mit
- Created: 2024-09-29T13:11:35.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2025-03-08T19:01:10.000Z (about 2 months ago)
- Last Synced: 2025-05-07T05:04:51.992Z (about 8 hours ago)
- Language: TypeScript
- Homepage:
- Size: 170 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Get-Or-Throw / Got
A convenience function for safely accessing values in dynamic objects and
arrays. It gets the value at a specified key or index, and throws an error if
the resulting value is `undefined`. Optionally, you can set a custom error
message.This was created to make it easy to adhere to Typescript's
[noUncheckedIndexedAccess](https://www.typescriptlang.org/tsconfig/#noUncheckedIndexedAccess)
setting, which is recommended for strict type checking.## Features
- Typescript assertions for type narrowing.
- Works with both objects and arrays.
- Supports negative indexing for arrays.
- Allows for custom error messages.
- Zero dependencies.
- Provides `got` as alias for `getOrThrow`## Installation
```bash
pnpm add get-or-throw
```...or use the equivalent for your package manager.
## Usage
The example code below uses the `got` alias but `getOrThrow` is also available
if you want to be more explicit.```ts
const arr = [1, 2, 3];
const value = got(arr, 1); // Output: 2/** Support for negative indexing */
const arr = [1, 2, 3];
const value = got(arr, -1); // Output: 3/** This will throw an error: "Index 3 is out of bounds." */
const value = got(arr, 3);const obj = { a: 1, b: 2, c: 3 };
const value = got(obj, "b"); // Output: 2/** This will throw an error: "Key "d" does not exist in the object." */
const value = got(obj, "d");/** This will throw an error: "Failed to find d" */
const key = "d";
const value = got(obj, key, `Failed to find ${key}`);/** Null is a valid value */
const arr = [1, null, 3];
const value = got(arr, 1); // Output: null/** This will throw an error: "Value at index 1 is undefined." */
const arr = [1, undefined, 3];
const value = got(arr, 1);/** Null is a valid value */
const obj = { a: 1, b: null, c: 3 };
const value = got(obj, "b"); // Output: null/** This will throw an error: "Value at key 'b' is undefined." */
const obj = { a: 1, b: undefined, c: 3 };
const value = got(obj, "b");
```