From d4dc64a2250c794a7628d4077f4970384114bae1 Mon Sep 17 00:00:00 2001 From: Camilla Marie Dalan Date: Mon, 9 Sep 2024 10:46:10 +0200 Subject: [PATCH] adds discriminated union for component types in simple table --- src/codegen/dataTypes/GenerateUnion.ts | 10 +++++++++- src/layout/SimpleTable/config.ts | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/codegen/dataTypes/GenerateUnion.ts b/src/codegen/dataTypes/GenerateUnion.ts index abb23264b7..8982370da9 100644 --- a/src/codegen/dataTypes/GenerateUnion.ts +++ b/src/codegen/dataTypes/GenerateUnion.ts @@ -3,12 +3,14 @@ import type { JSONSchema7 } from 'json-schema'; import { DescribableCodeGenerator, MaybeOptionalCodeGenerator } from 'src/codegen/CodeGenerator'; import type { CodeGenerator, Extract } from 'src/codegen/CodeGenerator'; +type UnionType = 'any' | 'discriminated'; /** * Generates a union of multiple types. In typescript this is a regular union, and in JsonSchema it is an 'anyOf'. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export class GenerateUnion[]> extends DescribableCodeGenerator> { private types: U; + private unionType: UnionType = 'any'; constructor(...types: U) { super(); @@ -21,6 +23,11 @@ export class GenerateUnion[]> extends DescribableCo this.types.push(type); } + setUnionType(type: UnionType) { + this.unionType = type; + return this; + } + toTypeScriptDefinition(symbol: string | undefined): string { const out = this.types.map((type) => type.toTypeScript()).join(' | '); @@ -28,9 +35,10 @@ export class GenerateUnion[]> extends DescribableCo } toJsonSchemaDefinition(): JSONSchema7 { + const schemaKey = this.unionType === 'discriminated' ? 'oneOf' : 'anyOf'; return { ...this.getInternalJsonSchema(), - anyOf: this.types.map((type) => type.toJsonSchema()), + [schemaKey]: this.types.map((type) => type.toJsonSchema()), }; } diff --git a/src/layout/SimpleTable/config.ts b/src/layout/SimpleTable/config.ts index 3e4e85595d..51f848f3b8 100644 --- a/src/layout/SimpleTable/config.ts +++ b/src/layout/SimpleTable/config.ts @@ -34,7 +34,7 @@ export const Config = new CG.component({ new CG.prop('hrefPath', new CG.str()), new CG.prop('textPath', new CG.str()), ), - ), + ).setUnionType('discriminated'), ), ).exportAs('ColumnConfig'), ),