From 31402598d44e733a84f3ea6277fc140e09d8d4cc Mon Sep 17 00:00:00 2001 From: Kir_Antipov Date: Sun, 5 Feb 2023 13:54:07 +0000 Subject: [PATCH] Made class that represents type union --- src/utils/typescript/typescript-union-type.ts | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/utils/typescript/typescript-union-type.ts diff --git a/src/utils/typescript/typescript-union-type.ts b/src/utils/typescript/typescript-union-type.ts new file mode 100644 index 0000000..c930a25 --- /dev/null +++ b/src/utils/typescript/typescript-union-type.ts @@ -0,0 +1,81 @@ +import { TypeScriptFormattingOptions } from "./typescript-formatting-options"; +import { TypeScriptTypeDefinition } from "./typescript-type-definition"; +import { TypeScriptTypeLiteral } from "./typescript-type-literal"; + +/** + * Represents a TypeScript union type definition. + */ +export class TypeScriptUnionType implements TypeScriptTypeDefinition { + /** + * An array of types that compose this union type. + */ + private readonly _composingTypes: readonly TypeScriptTypeDefinition[]; + + /** + * Constructs a new {@link TypeScriptUnionType} instance. + * + * @param composingTypes - The iterable of types composing the union. + */ + private constructor(composingTypes: readonly TypeScriptTypeDefinition[]) { + this._composingTypes = composingTypes; + } + + /** + * Creates a new {@link TypeScriptUnionType} instance. + * + * @param composingTypes - The iterable of types composing the union. + * + * @returns A new {@link TypeScriptUnionType} instance. + */ + static create(composingTypes: Iterable): TypeScriptUnionType { + const composingTypesArray = [...composingTypes]; + if (!composingTypesArray.length) { + composingTypesArray.push(TypeScriptTypeLiteral.NEVER); + } + + return new TypeScriptUnionType(composingTypesArray); + } + + /** + * @inheritdoc + */ + get isComposite(): true { + return true; + } + + /** + * @inheritdoc + */ + get isUnion(): true { + return true; + } + + /** + * @inheritdoc + */ + get isIntersection(): false { + return false; + } + + /** + * @inheritdoc + */ + get isAlias(): false { + return false; + } + + /** + * @inheritdoc + */ + composingTypes(): Iterable { + return this._composingTypes; + } + + /** + * @inheritdoc + */ + format(options?: TypeScriptFormattingOptions): string { + const formattedTypes = this._composingTypes.map(x => `(${x.format(options).trim()})`).join(" | "); + return formattedTypes; + } +}