Skip to content

objectenvy / SchemaToEnv

Type Alias: SchemaToEnv<T>

ts
type SchemaToEnv<T> = T extends {
  _output: infer O;
} ? ToEnv<O> : ToEnv<T>;

Defined in: typeUtils.ts:318

Extract the flat SCREAMING_SNAKE_CASE env record type from a Zod schema or a plain config type.

Type Parameters

Type ParameterDescription
TA Zod schema (z.ZodType) or a plain TypeScript config type.

Remarks

If T is a Zod schema (has _output), SchemaToEnv extracts the inferred output type and passes it to ToEnv. Otherwise, T is treated as a plain config type and passed directly to ToEnv. This makes the utility work for both SchemaToEnv<typeof zodSchema> and SchemaToEnv<ConfigType> patterns.

Use When

  • You have a Zod schema and want to derive the corresponding env variable type without manually writing ToEnv<z.infer<typeof schema>>.
  • You want to statically validate .env.example generators against a Zod schema.

Avoid When

  • You already have z.infer<typeof schema> available — use ToEnv<z.infer<typeof schema>> directly for clarity.

Pitfalls

  • NEVER pass a Zod v4 schema if the _output field is structured differently from v3 — BECAUSE SchemaToEnv uses _output heuristically; if the Zod version changes the field name, the type falls back to treating the schema object itself as a config type.

Example

ts
import type { SchemaToEnv } from 'objectenvy';
import { z } from 'zod';

const schema = z.object({
  port: z.number(),
  log: z.object({ level: z.string() })
});

type Env = SchemaToEnv<typeof schema>;
// { PORT: `${number}`; LOG_LEVEL: string }

See

ToEnv for direct use with plain config types

Released under the MIT License.