Skip to content

Instantly share code, notes, and snippets.

@Krisztiaan
Created September 29, 2021 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Krisztiaan/cc7562d1080ea0790a73241723e6f1f2 to your computer and use it in GitHub Desktop.
Save Krisztiaan/cc7562d1080ea0790a73241723e6f1f2 to your computer and use it in GitHub Desktop.
type AnyValue =
| { [key: string]: AnyValue }
| { [key: number]: AnyValue }
| AnyValue[]
| string
| number
| boolean
| null
| undefined
| symbol
| BigInt
| ((...args: AnyValue[]) => AnyValue);
type SerializableValue =
| { [key: string]: SerializableValue }
| { [key: number]: SerializableValue }
| SerializableValue[]
| string
| number
| boolean
| null
| undefined;
export default function toSerializable<
TInput extends { [key: string]: AnyValue } | { [key: number]: AnyValue } | AnyValue[] | AnyValue,
>(input: TInput): SerializableValue {
if (input == null) return input;
return Array.isArray(input)
? input
.filter(shouldKeep)
.map((item) => (typeof item === 'object' ? toSerializable(item) : item))
: Object.fromEntries(
Object.entries(input)
.filter(([, v]) => shouldKeep(v))
.map(([key, value]) => [key, typeof value === 'object' ? toSerializable(value) : value]),
);
}
// eslint-disable-next-line @typescript-eslint/ban-types
type MakeSerializable<TInput> = TInput extends BigInt | symbol | Function ? never : TInput;
function shouldKeep<TItem>(item: TItem): item is MakeSerializable<TItem> {
return !['function', 'symbol', 'bigint'].includes(typeof item);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment