Created
September 29, 2021 08:39
-
-
Save Krisztiaan/cc7562d1080ea0790a73241723e6f1f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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