JavaScript:获取对象属性未定义则抛错,求标准或第三方库实现
Hey there! I totally get what you're looking for— a ready-made function to validate required options like your example. Let's break down what's available:
Lodash: No Direct Out-of-the-Box Function
I’ve dug through Lodash’s docs too, and there’s no dedicated function that exactly matches your logic. That said, you can easily combine Lodash’s existing utilities to build a reusable helper that keeps things clean:
const _ = require('lodash'); // Reusable helper to check required options function getRequiredOption(options, key) { const value = _.get(options, key); if (value == null) { // Matches both null and undefined throw new Error(`${key} is required option`); } return value; } // Use it in your function function f(options) { const x = getRequiredOption(options, 'x'); // ... rest of your logic }
_.get is handy here because it safely accesses nested keys if you ever need that later, but even a simple check with _.has could work if you just want to verify existence before accessing.
Standard JavaScript: Build Your Own Minimal Helper
Since ES6+ doesn’t have a built-in function for this either, you can create a tiny, dependency-free helper that does exactly what you need:
function getRequiredOption(options, key) { const value = options[key]; if (value === null || value === undefined) { throw new Error(`${key} is required option`); } return value; } // Usage example function f(options) { const x = getRequiredOption(options, 'x'); // ... your logic here }
This is lightweight, easy to understand, and doesn’t require any external libraries at all.
Quick Note for TypeScript Users
If you’re using TypeScript, you can enforce required options at compile time with type definitions, but you’ll still want a runtime check like the above to handle cases where untyped data comes into your function (like API inputs).
内容的提问来源于stack exchange,提问作者Dylanthepiguy

