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]