Function: safeObjectAccess()
safeObjectAccess<
T
>(obj
:unknown
,key
:PropertyKey
,fallback
:T
,validator?
: (value
:unknown
) =>value is T
):T
Defined in: shared/utils/objectSafety.ts:35
Type-safe object property access with fallback.
Type Parametersโ
Tโ
T
Parametersโ
objโ
unknown
Object to access property from
keyโ
PropertyKey
Property key (string or symbol only)
fallbackโ
T
Fallback value if property doesn't exist or is wrong type
validator?โ
(value
: unknown
) => value is T
Optional type guard function to validate the property value
Returnsโ
T
Property value or fallback
Remarksโ
Only accepts string and symbol keys as these are the valid property key types in JavaScript. Number keys are automatically converted to strings by JavaScript, so use string keys directly to avoid confusion.
Exampleโ
const config: unknown = { timeout: 5000 };
const timeout = safeObjectAccess(config, "timeout", 10000);
// Returns 5000 if timeout exists and is correct type, otherwise 10000