private tryEmitUnion()

in src/type-generator.ts [347:381]


  private tryEmitUnion(typeName: string, def: JSONSchema4, fqn: string): EmittedType | undefined {
    const options = new Array<string>();
    for (const option of def.oneOf || def.anyOf || []) {
      if (!supportedUnionOptionType(option.type)) {
        return undefined;
      }

      const type = option.type === 'integer' ? 'number' : option.type;
      options.push(type);
    }

    const emitted: EmittedType = { type: typeName, toJson: x => `${x}?.value` };

    this.addCode(typeName, code => {
      this.emitDescription(code, fqn, def.description);

      code.openBlock(`export class ${typeName}`);

      for (const type of options) {
        const methodName = 'from' + type[0].toUpperCase() + type.substr(1);
        code.openBlock(`public static ${methodName}(value: ${type}): ${typeName}`);
        code.line(`return new ${typeName}(value);`);
        code.closeBlock();
      }

      code.openBlock('private constructor(public readonly value: any)');
      code.closeBlock();

      code.closeBlock();

      return emitted;
    });

    return emitted;
  }