Created
January 13, 2023 13:11
-
-
Save TorbjornHoltmon/502a575ac1f8604b3cb2e88e01996580 to your computer and use it in GitHub Desktop.
JSON type
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
type JsonPrimitives = string | number | boolean | String | Number | Boolean | null; | |
type NonJsonPrimitives = undefined | Function | symbol; | |
type SerializeType<T> = T extends JsonPrimitives | |
? T | |
: T extends NonJsonPrimitives | |
? never | |
: T extends { toJSON(): infer U } | |
? U | |
: T extends [] | |
? [] | |
: T extends [unknown, ...unknown[]] | |
? { | |
[k in keyof T]: T[k] extends NonJsonPrimitives ? null : SerializeType<T[k]>; | |
} | |
: T extends (infer U)[] | |
? (U extends NonJsonPrimitives ? null : SerializeType<U>)[] | |
: T extends object | |
? { | |
[k in keyof T as T[k] extends NonJsonPrimitives ? never : k]: SerializeType<T[k]>; | |
} | |
: never; | |
interface Thing { | |
keyForThing?: boolean; | |
deepValue?: DeepValue; | |
} | |
interface DeepValue { | |
something?: string; | |
} | |
interface SomethingInvalid { | |
valid: Thing; | |
invalid: () => {}; | |
} | |
type Result = SerializeType<Thing>; | |
type Result2 = SerializeType<SomethingInvalid>; | |
async function getFromCache<T>(fetcher: () => Promise<T>): Promise<SerializeType<T>> { | |
const result = await fetcher(); | |
return JSON.parse(JSON.stringify(result)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment