From 5e839b906da6f3d5e76d60680a64e38482fdd863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20Lo=CC=81pez=20Guevara?= Date: Tue, 17 Jan 2023 20:04:51 -0300 Subject: [PATCH] feat(envconfig): fix optional number --- src/envconfig.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/envconfig.ts b/src/envconfig.ts index 30891d5..aeb16c7 100644 --- a/src/envconfig.ts +++ b/src/envconfig.ts @@ -750,6 +750,11 @@ export const parse = < env[key] = (val?.split(",") || "").map(Number); } else { env[key] = Number(val); + if ( + !required && typeof original === "undefined" && isNaN(env[key]) + ) { + env[key] = undefined; + } } break; case type === "bool": @@ -812,7 +817,11 @@ export const parse = < type === "number" && (!split_values && isNaN(val) || split_values && val?.some(isNaN)) ) { - throw invalidNumberError(key, original, val); + if (!required && typeof original === "undefined") { + val = env[key] = undefined; + } else { + throw invalidNumberError(key, original, val); + } } if ( @@ -1610,6 +1619,18 @@ describe("complex marks", () => { assertEquals(parsed.myapp.super.nest.port, 3003); }); + it("should parse undefined on `number", () => { + const env = {}; + + const config = { + port: "`number", + } as const; + + const parsed = parse(env, config); + + assertEquals(parsed.port, undefined); + }); + it("should parse super nested `number with prefix override", () => { const env = { MYAPP_SUB_P1: "1",