Last active
June 7, 2022 11:12
-
-
Save danecando/e94ac395953e15ba6ca8dfa9b9a62497 to your computer and use it in GitHub Desktop.
SerializeType utility for converting a type to JSON
This file contains hidden or 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
// credit @colinhacks | |
// https://github.com/remix-run/remix/pull/1254 | |
type JSONPrimitives = string | number | boolean | null; | |
type NonJSONPrimitives = undefined | Function | symbol; | |
export type SerializeType<T> = T extends JSONPrimitives | |
? T | |
: T extends undefined | |
? undefined | |
: T extends { toJSON(): infer U } | |
? U | |
: T extends [] | |
? [] | |
: T extends [any, ...any[]] | |
? { | |
[k in keyof T]: T[k] extends NonJSONPrimitives | |
? null | |
: SerializeType<T[k]>; | |
} | |
: T extends (infer U)[] | |
? SerializeType<U>[] | |
: { | |
[k in keyof T as T[k] extends NonJSONPrimitives | |
? never | |
: k]: SerializeType<T[k]>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment