import { SimpleType , ObjectType , SourceFile } from "./internal" ; export class UnionType { private readonly unions = new Set < SimpleType > ( ) ; constructor ( private sourceFile ) { } spread ( ) { return Array . from ( this . unions ) ; } protected addUnion ( type ) { this . unions . add ( type ) ; } protected addUnions ( types ) { types . forEach ( ( type ) => { this . unions . add ( type ) ; } ) ; } /**
     * When generating a definition,
     * if the UnionType consists of a single `ObjectType`,
     * its interface definition should be used instead of type alias.
     */ generateInterfaceDefinitionOrTypeAlias ( name , isArray ) { if ( ! isArray && this . unions . size === 1 ) { const type = Array . from ( this . unions ) [ 0 ] ; if ( type instanceof ObjectType ) { this . sourceFile . internalInterfaces . removeOne ( type ) ; return `interface ${ name } ${ type . toDefinitionString ( ) }` ; } } return `type ${ name } = ${ this . withArray ( isArray ) };` ; } withArray ( isArray ) { let displayType = Array . from ( this . unions ) . map ( ( t ) => t . toString ( ) ) . join ( "&" ) ; if ( isArray && this . unions . size > 1 ) { displayType = `(${ displayType })` ; } return displayType + ( isArray ? "[]" : "" ) ; } containsFileField ( ) { return Array . from ( this . unions ) . some ( ( type ) => type instanceof ObjectType && type . containsFileField ( ) ) ; } }