Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/quicktype-typescript-input/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,30 @@ function patchGeneratorForBuiltinTypes(
};
}

// typescript-json-schema copies JSDoc `@type {string}` annotations into the
// generated schema verbatim. Strip the JSDoc braces so the value is a valid
// JSON Schema type.
function sanitizeTypeAnnotations(value: unknown): void {
if (Array.isArray(value)) {
value.forEach(sanitizeTypeAnnotations);
return;
}

if (value === null || typeof value !== "object") {
return;
}

const schema = value as Record<string, unknown>;
if (typeof schema.type === "string") {
const match = /^\{([^{}]+)\}$/.exec(schema.type);
if (match !== null) {
schema.type = match[1];
}
}

Object.values(schema).forEach(sanitizeTypeAnnotations);
}

// FIXME: We're stringifying and then parsing this schema again. Just pass around
// the schema directly.
export function schemaForTypeScriptSources(
Expand All @@ -151,6 +175,8 @@ export function schemaForTypeScriptSources(
patchGeneratorForBuiltinTypes(generator, program);

const schema = generateSchema(program, "*", settings, undefined, generator);
sanitizeTypeAnnotations(schema);

const uris: string[] = [];
let topLevelName = "";

Expand Down
17 changes: 17 additions & 0 deletions test/unit/typescript-input.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,23 @@ describe("schemaForTypeScriptSources", () => {
expect(schema.definitions.Person.type).toBe("object");
});

// https://github.com/glideapps/quicktype/issues/2695
test("strips braces from JSDoc type annotations", () => {
const { schema } = schemaForSource(`
export type Person = {
/**
* @type {string}
* @memberOf {Person}
*/
name: string;
};

export type MemberInfo = Required<Person>;
`);

expect(schema.definitions.Person.properties.name.type).toBe("string");
});

test("class property initializers become defaults", () => {
const { schema } = schemaForSource(`
export class Config {
Expand Down
Loading