Skip to content

objectenvy / safeObjectify

Function: safeObjectify()

Call Signature

ts
function safeObjectify<T, TOut>(options): 
  | {
  data: TOut;
  success: true;
}
  | {
  error: unknown;
  success: false;
};

Defined in: objectEnvy.ts:606

Non-throwing variant of objectify. Returns a discriminated union instead of throwing on validation failure or transform errors.

Type Parameters

Type Parameter
T extends ConfigObject
TOut extends ConfigObject

Parameters

ParameterType
optionsOmit<ObjectEnvyOptions<T>, "transform"> & { transform: (parsed) => TOut; }

Returns

| { data: TOut; success: true; } | { error: unknown; success: false; }

{ success: true; data: T } on success, or { success: false; error: unknown } on any thrown error. When a transform that widens the type is provided, data is typed as TOut.

Remarks

Catches all errors including ZodError (when a schema is provided) and any error thrown inside a transform callback. On ZodError, the original error is available as result.error.

Example

ts
const result = safeObjectify({ env: import.meta.env, prefix: 'VITE', schema: ConfigSchema });
if (!result.success) {
  console.error('Config invalid:', result.error);
  return;
}
const config = result.data;

See

objectify for the throwing variant

Call Signature

ts
function safeObjectify<T>(options?): 
  | {
  data: T;
  success: true;
}
  | {
  error: unknown;
  success: false;
};

Defined in: objectEnvy.ts:609

Non-throwing variant of objectify. Returns a discriminated union instead of throwing on validation failure or transform errors.

Type Parameters

Type ParameterDefault type
T extends ConfigObjectConfigObject

Parameters

ParameterType
options?ObjectEnvyOptions<T>

Returns

| { data: T; success: true; } | { error: unknown; success: false; }

{ success: true; data: T } on success, or { success: false; error: unknown } on any thrown error. When a transform that widens the type is provided, data is typed as TOut.

Remarks

Catches all errors including ZodError (when a schema is provided) and any error thrown inside a transform callback. On ZodError, the original error is available as result.error.

Example

ts
const result = safeObjectify({ env: import.meta.env, prefix: 'VITE', schema: ConfigSchema });
if (!result.success) {
  console.error('Config invalid:', result.error);
  return;
}
const config = result.data;

See

objectify for the throwing variant

Released under the MIT License.