Skip to content

Instantly share code, notes, and snippets.

@danecando
Last active June 7, 2022 11:12
Show Gist options
  • Save danecando/e94ac395953e15ba6ca8dfa9b9a62497 to your computer and use it in GitHub Desktop.
Save danecando/e94ac395953e15ba6ca8dfa9b9a62497 to your computer and use it in GitHub Desktop.
SerializeType utility for converting a type to JSON
// 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