Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: keyof typeof fields inside objects #2040

Merged
merged 3 commits into from
Aug 14, 2024
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
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"
}
}
}
Loading