From 7e40308a8a029fbae08f387026463bcb710c8d4e Mon Sep 17 00:00:00 2001 From: Dragory <2606411+Dragory@users.noreply.github.com> Date: Thu, 29 Apr 2021 00:46:21 +0300 Subject: [PATCH] Add tNormalizedNullOrUndefined and tNormalizedNullOptional tNormalizedNullOrUndefined: io-ts type that accepts null and undefined and normalizes both to undefined tNormalizedNullOptional: io-ts type that accepts the specified type or null/undefined. if null/undefined, the value is normalized to undefined. this allows creating optional config options that can be "removed" by setting their value to null. --- backend/src/utils.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/backend/src/utils.ts b/backend/src/utils.ts index 059ddac9..26889b3d 100644 --- a/backend/src/utils.ts +++ b/backend/src/utils.ts @@ -95,6 +95,24 @@ function typeIsArray(type: any): type is t.ArrayC { return type._tag === "ArrayType"; } +export const tNormalizedNullOrUndefined = new t.Type( + "tNormalizedNullOrUndefined", + (v): v is undefined => typeof v === "undefined", + (v, c) => (v == null ? t.success(undefined) : t.failure(v, c, "Value must be null or undefined")), + s => undefined, +); + +/** + * Similar to `tNullable`, but normalizes both `null` and `undefined` to `undefined`. + * This allows adding optional config options that can be "removed" by setting the value to `null`. + */ +export function tNormalizedNullOptional>(type: T) { + return t.union( + [type, tNormalizedNullOrUndefined], + `Optional<${type.name}>`, // Simplified name for errors and config schema views + ); +} + export type TDeepPartial = T extends t.InterfaceType ? TDeepPartialProps : T extends t.DictionaryType