Skip to content

Commit

Permalink
adds discriminated union for component types in simple table
Browse files Browse the repository at this point in the history
  • Loading branch information
cammiida committed Sep 9, 2024
1 parent 4861bd1 commit d4dc64a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/codegen/dataTypes/GenerateUnion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<U extends CodeGenerator<any>[]> extends DescribableCodeGenerator<Extract<U[number]>> {
private types: U;
private unionType: UnionType = 'any';

constructor(...types: U) {
super();
Expand All @@ -21,16 +23,22 @@ export class GenerateUnion<U extends CodeGenerator<any>[]> 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(' | ');

return symbol ? `type ${symbol} = ${out};` : out;
}

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()),
};
}

Expand Down
2 changes: 1 addition & 1 deletion src/layout/SimpleTable/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
),
Expand Down

0 comments on commit d4dc64a

Please sign in to comment.