lucis
lucis2y ago

Converting Typescript Types to JSON Schema (Props definition)?

Folks, We're creating a CMS solution using Deno and Fresh. For our product goals, we want to dynamically extract how UI components are configured using their Props declaration. Example: For this component
interface Props {
title: string
numberOfLines: number
}

export default MyComponent(props: Props) {
return <div>.,.
}
interface Props {
title: string
numberOfLines: number
}

export default MyComponent(props: Props) {
return <div>.,.
}
we should be able to extract (in dev time, we have a slight "build process" already in place) the Props declaration, and be able to generate a form for that. To generate the Form, we're using JSON Schema + react-json-schema-form (https://react-jsonschema-form.readthedocs.io/en/latest/) and, for that to happen, we need to transform the file above into a JSON Schema that defines exactly the data for that component's props. The question is: how can we accomplish that in a reliable way? We have a proof of concept working where we use deno doc file.ts --json (https://github.com/deco-cx/live/blob/main/utils/denoDoc.ts) and it's ok, but we need to manually "map" everything. Right now, we don't support Array<CustomObject> as a type for a prop, for example. We believe that there must be a more "native" way, that uses the same AST/metadata that Deno uses, that will handle most case for us. Edge cases are: - props with custom types defined elsewhere in the module and referenced in the props declaration. - props with types imported from other files - props with types imported using import_map.json We're aware of https://github.com/YousefED/typescript-json-schema but I'm pretty sure that it'll differ slightly to how Deno works. Do you have any suggestions?
7 Replies
lucis
lucis2y ago
cc @guifromrio @brasileiro_ @tgimenes
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Leokuma
Leokuma2y ago
An AST-based solution sounds too complex for a CMS. Personally I would avoid that strategy Can't you export the Props interface and import it in another script which would then generate and save the JSON schema to the filesystem? I guess you can iterate over Props with for in, Object.keys or something
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Sorikairo
Sorikairo2y ago
I would suggest that you look into decorators with “emitDecoratorMetadata” compilers option and “design:paramstype”, “design:type” metadata. This is what I use to generate open api schema from ts code. Yes it forces you to add decorators to your component and classes, but it can also be a way to white list what you want to generate schema for 😃
lucis
lucis2y ago
types in typescript are not something you can iterate over, there's no reflection for that. that's the main problem and why we need go to AST parsing
Leokuma
Leokuma2y ago
I knew I must be missing something 😅