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

Support serialization of object examples on unions #5180

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/compiler"
---

Fixed serialization of object examples on unions
3 changes: 2 additions & 1 deletion packages/compiler/src/lib/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,12 @@ function resolveUnions(program: Program, value: ObjectValue, type: Type): Type |
if (type.kind !== "Union") {
return type;
}
const exactValueType = program.checker.getValueExactType(value);
for (const variant of type.variants.values()) {
if (
ignoreDiagnostics(
program.checker.isTypeAssignableTo(
value.type.projectionBase ?? value.type,
exactValueType ?? value.type.projectionBase ?? value.type,
variant.type.projectionBase ?? variant.type,
value,
),
Expand Down
26 changes: 25 additions & 1 deletion packages/compiler/test/decorators/examples.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ describe("@example", () => {
});

describe("union", () => {
it("valid", async () => {
it("valid for union member reference", async () => {
const { program, examples, target } = await getExamplesFor(`
@example(test.a)
@test union test {a: "a", b: "b"}
Expand All @@ -182,6 +182,30 @@ describe("@example", () => {
expect(serializeValueAsJson(program, examples[0].value, target)).toEqual("a");
});

it("valid for object value", async () => {
const { program, examples, target } = await getExamplesFor(`
model A {
type: "a";
a: string;
}
model B {
type: "b";
b: numeric;
}

@example(#{
type: "a",
a: "a string",
})
@test union test {a: A, b: B}
`);
expect(examples).toHaveLength(1);
expect(serializeValueAsJson(program, examples[0].value, target)).toEqual({
type: "a",
a: "a string",
});
});

it("emit diagnostic for unassignable value", async () => {
const diagnostics = await diagnoseCode(`
@example(1)
Expand Down
Loading