Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Avoiding Obj.magic idioms?

$
0
0

I think the issue in your code comes from the fact you treat all these values as unknown or whatever the typescript type is supposed to be and then try to narrow down their types at runtime.

But ReScript is not like typescript, you’re not supposed to type all the possible cases of a given variable, you just encode the characteristics you need of these types, so you can use more constrained types in your bindings and you won’t need all these Obj.magic, for example:

module Dotenv = {
  type configOptions = {
    path?: string,
    processEnv?: dict<string>,
    quiet?: bool,
  }
  @unboxed type configCode = ENOENT | Other(string)
  type configError = private {code?: configCode}
  type configOutput = private {
    parsed?: dict<string>,
    error?: configError,
  }
  @module("dotenv")
  external config: configOptions => configOutput = "config"
}

// Load env files in order, applying overrides if enabled
let paths = [".env", "dev.env"]
let loadedFilesMut = []
let applyVars = _s => ()
paths->Array.forEach(path =>
  switch Dotenv.config({path, processEnv: dict{}, quiet: true}) {
  | {parsed} if parsed->Dict.isEmpty =>
    Console.warn(`File did not provide any env vars: ${path}`)
    loadedFilesMut->Array.push(path)
  | {parsed} =>
    applyVars(parsed)
    loadedFilesMut->Array.push(path)
  | {error: {code: ENOENT}} => ()
  | {error} => JsExn.throw(error)
  | _ => ()
  }
)

Viewing all articles
Browse latest Browse all 2592

Trending Articles