Avoiding Type Casting for Hostname Schema in Effect with Config and Schema

Hi all, I’m working on a way to load my environment variables with Effect. I’m using both Config and Schema, and created an envVar function to bridge the two.



I had to use NumberFromString in order to get Port to log. But I couldn’t figure out which built-in schema to use to get hostname to log. Casting works, but I’m not sure why.

This code runs, but iss there a way to avoid casting here?

import { Config, Schema as S } from "effect";

const allowedHostnames = S.Literal("localhost", "127.0.0.1", "0.0.0.0");
type Hostname = typeof allowedHostnames.Type;

const allowedPorts = S.NumberFromString.pipe(S.between(1, 65535));
type Port = typeof allowedPorts.Type;

const appConfig = Config.all({
  host: envVar<Hostname>("HOST", allowedHostnames as S.Schema<Hostname, string>), // how to avoid casting?
  port: envVar<Port>("PORT", allowedPorts), // this works
});

function envVar<A>(
  name: string,
  schema: S.Schema<A, string>
): Config.Config<A> {
  return S.Config(name, schema);
}

const program = Effect.gen(function* () {
  const app = yield* appConfig
  console.log(`ok: ${app.host}`)
  console.log(`ok: ${app.port}`)
})

Effect.runSync(program)
Was this page helpful?