/** * Flattens object types to a single level object, where types like `{ data: { person: { age: number } } }` are converted to: * ``` * { * 'data': { person: { age: number } }, * 'data.person': { age: number } * 'data.person.age': number * } * ``` */ type FlattenObject = CollapseEntries>; type Entry = { key: string; value: unknown; }; type EmptyEntry = { key: ''; value: TValue; }; type ExcludedTypes = Date | Set | Map; type ArrayEncoder = `[${bigint}]`; type EscapeArrayKey = TKey extends `${infer TKeyBefore}.${ArrayEncoder}${infer TKeyAfter}` ? EscapeArrayKey<`${TKeyBefore}${ArrayEncoder}${TKeyAfter}`> : TKey; type CollapseEntries = { [E in TEntry as EscapeArrayKey]: E['value']; }; type CreateArrayEntry = OmitItself; type OmitItself = TValue extends TValueInitial ? EmptyEntry : OmitExcludedTypes; type OmitExcludedTypes = TValue extends ExcludedTypes ? EmptyEntry : CreateObjectEntries; type NonUnderscoreString = T extends `_${string}` ? never : T; type StringKeys = Extract; type NestedValue, TValueInitial> = CreateArrayEntry extends infer TNestedValue ? TNestedValue extends Entry ? TNestedValue['key'] extends '' ? { key: TKey; value: TNestedValue['value']; } : { key: `${TKey}.${TNestedValue['key']}`; value: TNestedValue['value']; } | { key: TKey; value: TValue[TKey]; } : never : never; type ValidKey, TValueInitial> = TKey extends NonUnderscoreString ? NestedValue : never; type CreateObjectEntries = TValue extends object ? { [TKey in StringKeys]-?: ValidKey; }[StringKeys] : EmptyEntry; export { ExcludedTypes, FlattenObject };