From 459fc9563cceaff5dcedf11b2d6073b74e0e1a05 Mon Sep 17 00:00:00 2001 From: tadelesh Date: Tue, 9 Jul 2024 14:12:07 +0800 Subject: [PATCH 1/2] fix wrong handling for one variant union --- .../src/types.ts | 3 ++- .../test/types/union-types.test.ts | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/typespec-client-generator-core/src/types.ts b/packages/typespec-client-generator-core/src/types.ts index f30295d154..e07de8adf2 100644 --- a/packages/typespec-client-generator-core/src/types.ts +++ b/packages/typespec-client-generator-core/src/types.ts @@ -354,7 +354,8 @@ export function getSdkUnionWithDiagnostics( return diagnostics.wrap(diagnostics.pipe(getAnyType(context, type))); } - if (nonNullOptions.length === 1) { + // if a union is `type | null`, then we will return a nullable wrapper type of the type + if (nonNullOptions.length === 1 && nullOption !== undefined) { retval = diagnostics.pipe(getClientTypeWithDiagnostics(context, nonNullOptions[0], operation)); } else if ( // judge if the union can be converted to enum diff --git a/packages/typespec-client-generator-core/test/types/union-types.test.ts b/packages/typespec-client-generator-core/test/types/union-types.test.ts index e55230d393..aec84baa02 100644 --- a/packages/typespec-client-generator-core/test/types/union-types.test.ts +++ b/packages/typespec-client-generator-core/test/types/union-types.test.ts @@ -584,4 +584,26 @@ describe("typespec-client-generator-core: union types", () => { strictEqual(unionAsEnumInternal.usage, UsageFlags.Input | UsageFlags.Output); strictEqual(unionAsEnumInternal.access, "internal"); }); + + it("union with only one literal", async function () { + await runner.compileWithBuiltInService( + ` + @usage(Usage.input | Usage.output) + @access(Access.public) + model Test { + name: TestUnion; + } + + union TestUnion { + "A" + } + ` + ); + const sdkType = getSdkTypeHelper(runner); + strictEqual(sdkType.kind, "enum"); + strictEqual(sdkType.name, "TestUnion"); + const values = sdkType.values; + strictEqual(values.length, 1); + strictEqual(values[0].value, "A"); + }); }); From dc338da891ad6b8238098f78dad20c301a5d39fe Mon Sep 17 00:00:00 2001 From: tadelesh Date: Tue, 9 Jul 2024 14:12:52 +0800 Subject: [PATCH 2/2] changelog --- .../changes/fix_one_variant_union-2024-6-9-14-12-37.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .chronus/changes/fix_one_variant_union-2024-6-9-14-12-37.md diff --git a/.chronus/changes/fix_one_variant_union-2024-6-9-14-12-37.md b/.chronus/changes/fix_one_variant_union-2024-6-9-14-12-37.md new file mode 100644 index 0000000000..2f6a54278d --- /dev/null +++ b/.chronus/changes/fix_one_variant_union-2024-6-9-14-12-37.md @@ -0,0 +1,7 @@ +--- +changeKind: fix +packages: + - "@azure-tools/typespec-client-generator-core" +--- + +fix wrong handling for one variant union \ No newline at end of file