Skip to content

Commit

Permalink
fix: keyof typeof fields inside objects (#2040)
Browse files Browse the repository at this point in the history
  • Loading branch information
arthurfiorette authored Aug 14, 2024
1 parent 7ad481b commit 0abc89f
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/NodeParser/ObjectLiteralExpressionNodeParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class ObjectLiteralExpressionNodeParser implements SubNodeParser {
const referenced = this.checker.typeToTypeNode(
this.checker.getTypeAtLocation(spread.expression),
undefined,
ts.NodeBuilderFlags.NoTypeReduction,
ts.NodeBuilderFlags.NoTruncation,
);

if (!referenced) {
Expand All @@ -63,13 +63,31 @@ export class ObjectLiteralExpressionNodeParser implements SubNodeParser {
return [];
}

if (!t.name || !("initializer" in t)) {
if (!t.name) {
throw new UnknownNodeError(t);
}

let type: ts.Node | undefined;

if (ts.isShorthandPropertyAssignment(t)) {
type = this.checker.typeToTypeNode(
this.checker.getTypeAtLocation(t),
undefined,
ts.NodeBuilderFlags.NoTruncation,
);
} else if (ts.isPropertyAssignment(t)) {
type = t.initializer;
} else {
type = t;
}

if (!type) {
throw new ExpectationFailedError("Could not find type for property", t);
}

return new ObjectProperty(
t.name.getText(),
this.childNodeParser.createType(t.initializer, context),
this.childNodeParser.createType(type, context),
!(t as any).questionToken,
);
});
Expand Down
1 change: 1 addition & 0 deletions test/valid-data-type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ describe("valid-data-type", () => {

it("lowercase", assertValidSchema("lowercase", "MyType"));
it("const-spread", assertValidSchema("const-spread", "MyType"));
it("keyof-typeof-x", assertValidSchema("keyof-typeof-x", "MyType"));

it("promise-extensions", assertValidSchema("promise-extensions", "*"));

Expand Down
3 changes: 3 additions & 0 deletions test/valid-data/keyof-typeof-x/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const myprop = 0;
export const mymap = { myprop };
export type MyType = keyof typeof mymap;
10 changes: 10 additions & 0 deletions test/valid-data/keyof-typeof-x/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"$ref": "#/definitions/MyType",
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"MyType": {
"const": "myprop",
"type": "string"
}
}
}

0 comments on commit 0abc89f

Please sign in to comment.