quicktype icon indicating copy to clipboard operation
quicktype copied to clipboard

[Typescript] Top-level array don't get generated

Open SBrandeis opened this issue 1 year ago • 1 comments

Hello there

I'm trying to use quicktype-core to generate typescript interfaces from the following JSON schema.

The input JSON schema
{
	"$schema": "http://json-schema.org/draft-06/schema#",
	"title": "TextClassificationOutput",
	"type": "array",
	"items": {
		"type": "object",
		"title": "TextClassificationOutputElement",
		"properties": {
			"label": {
				"type": "string",
			},
			"score": {
				"type": "number",
			}
		},
		"required": ["label", "score"]
	}
}

However, the generated Typescript types are not what I am expecting:

  • The "top-level" array type is not generated
  • The name for the "inner" object definition does not match the title attribute
The generated Typescript code
export interface TextClassificationOutput {
    label: string;
    score: number;
    [property: string]: any;
}

I am expecting something like this instead:

export type TextClassificationOutput = TextClassificationOutputElement[];

export interface TextClassificationOutputElement {
    label: string;
    score: number;
    [property: string]: any;
}
The code generation script (typescript)
import type { SerializedRenderResult } from "quicktype-core";
import { quicktype, InputData, JSONSchemaInput, FetchingJSONSchemaStore } from "quicktype-core";
import * as fs from "fs/promises";

async function generateTypescript(): Promise<SerializedRenderResult> {
        const schema = new JSONSchemaInput(new FetchingJSONSchemaStore());
	await schema.addSource({
		name: `text-generation-output`,
		schema: await fs.readFile(`./schema.json`, { encoding: "utf-8" }),
	});
	const inputData = new InputData();
	inputData.addInput(schema);

	return await quicktype({
		inputData,
		lang: "typescript",
		alphabetizeProperties: true,
		rendererOptions: {
			"just-types": true,
			"nice-property-names": true,
			"prefer-unions": true,
			"prefer-const-values": true,
			"explicit-unions": true,
			"runtime-typecheck": false,
		},
	});
}

I'm happy to contribute a fix to this, but I can't wrap my head around the naming attribution code, and I don't know where to start. Some pointers would be greatly appreciated.

SBrandeis avatar Jan 25 '24 12:01 SBrandeis

If you change: name: `text-generation-output`,

to: name: `#/definitions/`,

it should work!

kmturley avatar Feb 20 '24 00:02 kmturley