gvergnaud / hotscript

A library of composable functions for the type-level! Transform your TypeScript types in any way you want using functions you already know.
3.51k stars 59 forks source link

fix(TransformObjectDeep): remove `| undefined` in `Array` case #91

Open DrJume opened 1 year ago

DrJume commented 1 year ago

Thank you so much for this library! I am using it to patch deeply nested auto-generated types from https://github.com/payloadcms/payload.

Based on the name of a property, I am applying Required<T> for this property.

E.g: Transform

{
  x: {
    id?: string | undefined,
    ...
  },
  ...
}

to

{
  x: {
    id: string,
    ...
  },
  ...
}

I only found the internal type TransformObjectDeep to help me with this use case.

import { type ComposeLeft, type Fn } from 'hotscript'
import { type TransformObjectDeep } from 'hotscript/dist/internals/objects/impl/objects'
import { type SetRequired } from 'type-fest'

interface IdRequiredFn extends Fn {
  return: this['args'] extends [infer obj]
    ? obj extends { id?: string }
      ? SetRequired<obj, 'id'>
      : obj
    : never
}

type FixPayloadTypes<T> = TransformObjectDeep<
  ComposeLeft<[IdRequiredFn]>, // I am also using other transform Fns
  T
>

But by using TransformObjectDeep all properties with Array<T> type get "unioned" with undefined, causing access to the items to fail. What is the reason for adding undefined to the type?