ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.46k stars 31 forks source link

Dynamically create a schema from a function #164

Closed aliyss closed 1 year ago

aliyss commented 1 year ago

Just in case anyone is wondering how to dynamically create a schema from a function and have it typed correctly here is an example.

import type { JSONSchema7TypeName } from "json-schema";
import type { FromSchema, JSONSchema } from "json-schema-to-ts";

export enum FieldType {
  INPUT = "input",
}

export interface AddFieldButtonItem {
  type: JSONSchema7TypeName;
}

export const fieldTypes: Record<FieldType, AddFieldButtonItem> = {
  [FieldType.INPUT]: {
    type: "string",
  },
}

export const fieldSchemaBase = (fieldType: FieldType) => {
  return {
    title: {
      title: "Field Title",
      type: "string",
    },
    default: {
      title: "Default Value",
      type: fieldTypes[fieldType].type,
    },
  } as const;
};

export const fieldSchema = (fieldType: FieldType) => {
  return {
    type: "object",
    additionalProperties: false,
    properties: {
      ...fieldSchemaBase(fieldType),
    },
    required: ["title"],
  } as const satisfies JSONSchema;
};

type FieldSchemaFunction = ReturnType<typeof fieldSchema>;
export type FieldSchema = FromSchema<FieldSchemaFunction>;
aliyss commented 1 year ago

Closing as this is just for people googling who are googling.