Skip to content

Instantly share code, notes, and snippets.

@clinuxrulz
Created December 23, 2024 01:08
Show Gist options
  • Save clinuxrulz/23b9df247f452c55207585d11746f059 to your computer and use it in GitHub Desktop.
Save clinuxrulz/23b9df247f452c55207585d11746f059 to your computer and use it in GitHub Desktop.
type Extract<Type, Union> = Type extends Union ? Type : never;
export type TypeSchema<A> =
TypeSchemaInvariantMap<unknown, A> |
TypeSchemaRecursive<A> |
{ type: "MaybeUndefined", elemTypeSchema: TypeSchema<NonNullable<A>>, } | (
A extends ({ has: true, value: unknown, } | { has: false, }) ? { type: "Optional", elemTypeSchema: TypeSchema<Extract<A, { value: unknown, }>["value"]>, } :
A extends boolean ? { type: "Boolean", } :
A extends number ? { type: "Number", } :
A extends string ? { type: "String", possibleValues?: string[], } :
A extends any[] ? { type: "Array", elemTypeSchema: TypeSchema<A[number]>, } :
A extends { type: string } ? { type: "Union", parts: { [key in Extract<A,{ type: string, }>["type"]]: PropertiesSchema2<Omit<Extract<A, { type: key, }>, "type">> } } :
never
) | (
A extends any ? (
{
type: "Object",
properties: PropertiesSchema2<A>,
} |
{ type: "Json", }
) :
never
);
type TypeSchemaInvariantMap<A,B> = {
type: "InvMap",
typeSchema: TypeSchema<A>,
fn1: (a: A) => B,
fn2: (b: B) => A,
};
type TypeSchemaRecursive<A> = {
type: "Recursive",
typeSchema: () => TypeSchema<A>,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment