Closed aliyss closed 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>;
Closing as this is just for people googling who are googling.
Just in case anyone is wondering how to dynamically create a schema from a function and have it typed correctly here is an example.