Skip to content

Instantly share code, notes, and snippets.

@JosXa
Created May 23, 2024 18:25
Show Gist options
  • Save JosXa/822f880443e6f735057cb1f21a08dce0 to your computer and use it in GitHub Desktop.
Save JosXa/822f880443e6f735057cb1f21a08dce0 to your computer and use it in GitHub Desktop.
// Name: JSON to TypeScript
// Description: Convert some JSON to TypeScript models
import "@johnlindquist/kit"
import jsonToTS from "json-to-ts"
import { submitShortcut } from "@johnlindquist/kit/core/utils"
import { refreshable } from "@josxa/kit-utils"
import { crudArg } from "@josxa/kit-utils"
import ModernError from "modern-errors"
let json = args[0]
if (!json) {
json = await editor({
language: "json",
validate(input: string): true | string {
try {
JSON.parse(input)
return true
} catch (err) {
return ModernError.normalize(err).message
}
},
shortcuts: [submitShortcut],
})
}
const rootName = await crudArg("Name of the root type?")
const options: Parameters<typeof jsonToTS>[1] = {
rootName,
useTypeAlias: true,
}
await refreshable(async ({ refresh }) => {
let types = ""
try {
types = `${jsonToTS(JSON.parse(json), options).join("\n\n")}\n`
} catch (error) {
const hint = ModernError.normalize(error).message
setHint(hint)
exit()
}
if (options.useTypeAlias) {
types = types.replaceAll(/^type /g, "export type ")
} else {
types = types.replaceAll(/^interface /g, "export interface ")
}
await editor({
value: types,
language: "ts",
shortcuts: [
{
key: `${cmd}+shift+t`,
name: `Use ${options.useTypeAlias ? "Interfaces" : "Types"}`,
onPress: () => {
options.useTypeAlias = !options.useTypeAlias
refresh()
},
visible: true,
bar: "right",
},
{
name: "Copy to Clipboard",
key: `${cmd}+shift+c`,
onPress: async (input) => {
await clipboard.writeText(input)
setHint("Copied to clipboard")
},
visible: true,
bar: "right",
},
],
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment