From a485ebaf74176c52d36f99ad9b33eda6284c07c5 Mon Sep 17 00:00:00 2001 From: itsMapleLeaf <19603573+itsMapleLeaf@users.noreply.github.com> Date: Sun, 24 Apr 2022 16:05:00 -0500 Subject: [PATCH] improve pruneNullishValues + test --- .../helpers/prune-nullish-values.test.ts | 33 +++++++++++++++++++ .../reacord/helpers/prune-nullish-values.ts | 27 +++++++++++---- 2 files changed, 54 insertions(+), 6 deletions(-) create mode 100644 packages/reacord/helpers/prune-nullish-values.test.ts diff --git a/packages/reacord/helpers/prune-nullish-values.test.ts b/packages/reacord/helpers/prune-nullish-values.test.ts new file mode 100644 index 0000000..aedbe2e --- /dev/null +++ b/packages/reacord/helpers/prune-nullish-values.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from "vitest" +import { PruneNullishValues, pruneNullishValues } from "./prune-nullish-values" + +test("pruneNullishValues", () => { + type InputType = { + a: string + b: string | null | undefined + c?: string + d: { + a: string + b: string | undefined + } + } + + const input: InputType = { + a: "a", + b: null, + c: undefined, + d: { + a: "a", + b: undefined, + }, + } + + const output: PruneNullishValues = { + a: "a", + d: { + a: "a", + }, + } + + expect(pruneNullishValues(input)).toEqual(output) +}) diff --git a/packages/reacord/helpers/prune-nullish-values.ts b/packages/reacord/helpers/prune-nullish-values.ts index 2729990..0324dc6 100644 --- a/packages/reacord/helpers/prune-nullish-values.ts +++ b/packages/reacord/helpers/prune-nullish-values.ts @@ -18,10 +18,25 @@ export function pruneNullishValues(input: T): PruneNullishValues { return result } -type PruneNullishValues = Input extends ReadonlyArray - ? ReadonlyArray> - : Input extends object - ? { - [Key in keyof Input]: NonNullable - } +export type PruneNullishValues = Input extends object + ? OptionalKeys< + { [Key in keyof Input]: NonNullable> }, + KeysWithNullishValues + > : Input + +type OptionalKeys = Omit & { + [Key in Keys]?: Input[Key] +} + +type KeysWithNullishValues = NonNullable< + Values<{ + [Key in keyof Input]: null extends Input[Key] + ? Key + : undefined extends Input[Key] + ? Key + : never + }> +> + +type Values = Input[keyof Input]