npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

safe-object-access

v1.1.0

Published

A robust, type-safe utility for safely accessing deeply nested object properties using string paths with full TypeScript autocomplete support.

Readme

safe-object-access

License: MIT GitHub

A robust, strongly-typed TypeScript utility for safely accessing deeply nested object properties using string paths.

Features

  • 🔒 Type-Safe Paths: TypeScript validates your string paths against the object's shape (autocomplete supported!).
  • 🎯 Return Type Inference: The return value is automatically typed based on the path (no more any).
  • 🛡️ Safe Access: Prevents crashes when accessing properties on undefined or null.
  • 📦 Bracket Notation: Supports both dot notation (users.0.name) and bracket notation (users[0].name).
  • ⚡️ High Performance: Built-in path memoization for lightning-fast repeated access in React render loops.
  • 🛠️ Configurable Fallbacks: Optionally treat null or empty strings as missing values.
  • 🔍 Debug Mode: Detailed console warnings to pinpoint exactly where path traversal fails.
  • 🚫 Prototype Protection: Automatically prevents access to __proto__, constructor, and prototype for security.

Installation

npm install safe-object-access

Usage

Basic Usage

import { safeGet } from 'safe-object-access';

const user = {
  profile: {
    name: 'Alice',
    settings: {
      theme: 'dark' as 'dark' | 'light'
    }
  },
  tags: ['admin', 'editor']
};

//  Fully typed string path with autocomplete!
// inferred type: "dark" | "light" | undefined
const theme = safeGet(user, 'profile.settings.theme'); 

//  Supports Array indices (dot or bracket)
// inferred type: string | undefined
const firstTag = safeGet(user, 'tags[0]'); 

// Default values handled correctly
// inferred type: "dark" | "light"
const safeTheme = safeGet(user, 'profile.settings.theme', 'light');

Advanced Usage

You can pass an optional options object as the fourth argument to customize how values are retrieved.

Handling null or Empty Strings

By default, safeGet only uses the default value if the result is undefined. Use these flags to handle other "empty" states:

const data = { bio: null, draft: "" };

// Treat null as missing
const bio = safeGet(data, 'bio', 'No bio yet', { treatNullAsMissing: true });

// Treat empty string as missing
const draft = safeGet(data, 'draft', 'Start typing...', { treatEmptyStringAsMissing: true });

Debugging Paths

If a path is returning a default value and you don't know why, enable debug mode to see exactly where the traversal stopped in the console.

safeGet(user, 'profile.addr.city', 'N/A', { debug: true });
// Console: [safeGet] Key "addr" does not exist on object.

Usage with React

This library is perfect for React applications where data shapes might be unpredictable or when mapping over keys.

import { safeGet } from 'safe-object-access';

interface UserData {
  user: {
    details?: {
      bio?: string;
    };
  };
}

const UserBio = ({ data }: { data: UserData }) => {
  // TypeScript will autocomplete the path "user.details.bio"
  const bio = safeGet(data, 'user.details.bio', 'No bio available');

  return <p>{bio}</p>;
};

When to use vs. Optional Chaining

| Feature | safeGet(obj, 'path.to.key') | Optional Chaining (obj?.path?.to?.key) | | :--- | :--- | :--- | | Dynamic Paths | ✅ Best Use Case. Can use variables for paths. | ❌ Not possible. Paths must be hardcoded. | | Type Safety | ✅ Types validated against string path. | ✅ Standard TS behavior. | | Syntax | Function call. | Native operator. | | Use Case | CMS content, deeply nested config, dynamic property access. | Standard static property access. |

When NOT to use safe-object-access

  1. Simple, Static Access: If you know the path at compile time and it's short, just use optional chaining: user?.profile?.name. It's faster and requires no library.
  2. Performance Critical Loops: While optimized, parsing string paths is slower than direct access. Avoid using inside tight loops (thousands of iterations) if raw performance is critical.

API

safeGet<T, P>(obj, path, defaultValue?, options?)

  • obj: The source object.
  • path: A string representing the path (e.g., 'a.b.c' or 'a[0].b'). Strictly typed to conform to T.
  • defaultValue (optional): A value to return if the resolution fails or returns undefined.
  • options (optional):
    • treatNullAsMissing: (boolean) If true, returns defaultValue when the resolved value is null.
    • treatEmptyStringAsMissing: (boolean) If true, returns defaultValue when the resolved value is "".
    • debug: (boolean) If true, logs helpful debugging information to the console if the traversal fails.

Returns the value at the path (strictly typed) or the default value.

🤝 Contributing

Found a bug or have a feature request?

  1. Fork the GitHub Repository.
  2. Create your feature branch (git checkout -b feature/AmazingFeature).
  3. Commit your changes (git commit -m 'Add some AmazingFeature').
  4. Push to the branch (git push origin feature/AmazingFeature).
  5. Open a Pull Request.

📄 License

Distributed under the MIT License. See LICENSE for more information.