diff --git a/head/schema-csharp/test/inputs/schema/named-class-union.schema/default/QuickType.cs b/head/schema-csharp/test/inputs/schema/named-class-union.schema/default/QuickType.cs
new file mode 100644
index 0000000..7fe3949
--- /dev/null
+++ b/head/schema-csharp/test/inputs/schema/named-class-union.schema/default/QuickType.cs
@@ -0,0 +1,70 @@
+// <auto-generated />
+//
+// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
+//
+//    using QuickType;
+//
+//    var topLevel = TopLevel.FromJson(jsonString);
+#nullable enable
+#pragma warning disable CS8618
+#pragma warning disable CS8601
+#pragma warning disable CS8602
+#pragma warning disable CS8603
+#pragma warning disable CS8604
+#pragma warning disable CS8625
+#pragma warning disable CS8765
+
+namespace QuickType
+{
+    using System;
+    using System.Collections.Generic;
+
+    using System.Globalization;
+    using Newtonsoft.Json;
+    using Newtonsoft.Json.Converters;
+
+    public partial class TopLevel
+    {
+        [JsonProperty("op", Required = Required.Always)]
+        public Foo Op { get; set; }
+    }
+
+    public partial class Foo
+    {
+        [JsonProperty("foo", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? FooFoo { get; set; }
+
+        [JsonProperty("bar", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
+        public string? Bar { get; set; }
+    }
+
+    public partial class TopLevel
+    {
+        public static TopLevel FromJson(string json) => JsonConvert.DeserializeObject<TopLevel>(json, QuickType.Converter.Settings);
+    }
+
+    public static partial class Serialize
+    {
+        public static string ToJson(this TopLevel self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
+    }
+
+    internal static partial class Converter
+    {
+        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
+        {
+            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
+            DateParseHandling = DateParseHandling.None,
+            Converters =
+            {
+                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
+            },
+        };
+    }
+}
+#pragma warning restore CS8618
+#pragma warning restore CS8601
+#pragma warning restore CS8602
+#pragma warning restore CS8603
+#pragma warning restore CS8604
+#pragma warning restore CS8625
+#pragma warning restore CS8765
diff --git a/head/schema-csharp-SystemTextJson/test/inputs/schema/named-class-union.schema/default/QuickType.cs b/head/schema-csharp-SystemTextJson/test/inputs/schema/named-class-union.schema/default/QuickType.cs
new file mode 100644
index 0000000..21db041
--- /dev/null
+++ b/head/schema-csharp-SystemTextJson/test/inputs/schema/named-class-union.schema/default/QuickType.cs
@@ -0,0 +1,177 @@
+// <auto-generated />
+//
+// To parse this JSON data, add NuGet 'System.Text.Json' then do:
+//
+//    using QuickType;
+//
+//    var topLevel = TopLevel.FromJson(jsonString);
+#nullable enable
+#pragma warning disable CS8618
+#pragma warning disable CS8601
+#pragma warning disable CS8602
+#pragma warning disable CS8603
+
+namespace QuickType
+{
+    using System;
+    using System.Collections.Generic;
+
+    using System.Text.Json;
+    using System.Text.Json.Serialization;
+    using System.Globalization;
+
+    public partial class TopLevel
+    {
+        [JsonRequired]
+        [JsonPropertyName("op")]
+        public Foo Op { get; set; }
+    }
+
+    public partial class Foo
+    {
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("foo")]
+        public string? FooFoo { get; set; }
+
+        [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
+        [JsonPropertyName("bar")]
+        public string? Bar { get; set; }
+    }
+
+    public partial class TopLevel
+    {
+        public static TopLevel FromJson(string json) => JsonSerializer.Deserialize<TopLevel>(json, QuickType.Converter.Settings);
+    }
+
+    public static partial class Serialize
+    {
+        public static string ToJson(this TopLevel self) => JsonSerializer.Serialize(self, QuickType.Converter.Settings);
+    }
+
+    internal static partial class Converter
+    {
+        public static readonly JsonSerializerOptions Settings = new(JsonSerializerDefaults.General)
+        {
+            Converters =
+            {
+                new DateOnlyConverter(),
+                new TimeOnlyConverter(),
+                IsoDateTimeOffsetConverter.Singleton
+            },
+        };
+    }
+    
+    public class DateOnlyConverter : JsonConverter<DateOnly>
+    {
+        private readonly string serializationFormat;
+        public DateOnlyConverter() : this(null) { }
+
+        public DateOnlyConverter(string? serializationFormat)
+        {
+                this.serializationFormat = serializationFormat ?? "yyyy-MM-dd";
+        }
+
+        public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                var value = reader.GetString();
+                return DateOnly.Parse(value!);
+        }
+
+        public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
+                => writer.WriteStringValue(value.ToString(serializationFormat));
+    }
+
+    public class TimeOnlyConverter : JsonConverter<TimeOnly>
+    {
+        private readonly string serializationFormat;
+
+        public TimeOnlyConverter() : this(null) { }
+
+        public TimeOnlyConverter(string? serializationFormat)
+        {
+                this.serializationFormat = serializationFormat ?? "HH:mm:ss.fff";
+        }
+
+        public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                var value = reader.GetString();
+                return TimeOnly.Parse(value!);
+        }
+
+        public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
+                => writer.WriteStringValue(value.ToString(serializationFormat));
+    }
+
+    internal class IsoDateTimeOffsetConverter : JsonConverter<DateTimeOffset>
+    {
+        public override bool CanConvert(Type t) => t == typeof(DateTimeOffset);
+
+        private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
+
+        private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
+        private string? _dateTimeFormat;
+        private CultureInfo? _culture;
+
+        public DateTimeStyles DateTimeStyles
+        {
+                get => _dateTimeStyles;
+                set => _dateTimeStyles = value;
+        }
+
+        public string? DateTimeFormat
+        {
+                get => _dateTimeFormat ?? string.Empty;
+                set => _dateTimeFormat = (string.IsNullOrEmpty(value)) ? null : value;
+        }
+
+        public CultureInfo Culture
+        {
+                get => _culture ?? CultureInfo.CurrentCulture;
+                set => _culture = value;
+        }
+
+        public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
+        {
+                string text;
+
+
+                if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
+                        || (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
+                {
+                        value = value.ToUniversalTime();
+                }
+
+                text = value.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
+
+                writer.WriteStringValue(text);
+        }
+
+        public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+        {
+                string? dateText = reader.GetString();
+
+                if (string.IsNullOrEmpty(dateText) == false)
+                {
+                        if (!string.IsNullOrEmpty(_dateTimeFormat))
+                        {
+                                return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
+                        }
+                        else
+                        {
+                                return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
+                        }
+                }
+                else
+                {
+                        return default(DateTimeOffset);
+                }
+        }
+
+
+        public static readonly IsoDateTimeOffsetConverter Singleton = new IsoDateTimeOffsetConverter();
+    }
+}
+#pragma warning restore CS8618
+#pragma warning restore CS8601
+#pragma warning restore CS8602
+#pragma warning restore CS8603
diff --git a/head/schema-dart/test/inputs/schema/named-class-union.schema/default/TopLevel.dart b/head/schema-dart/test/inputs/schema/named-class-union.schema/default/TopLevel.dart
new file mode 100644
index 0000000..6f1bd70
--- /dev/null
+++ b/head/schema-dart/test/inputs/schema/named-class-union.schema/default/TopLevel.dart
@@ -0,0 +1,45 @@
+// To parse this JSON data, do
+//
+//     final topLevel = topLevelFromJson(jsonString);
+
+import 'dart:convert';
+
+TopLevel topLevelFromJson(String str) => TopLevel.fromJson(json.decode(str));
+
+String topLevelToJson(TopLevel data) => json.encode(data.toJson());
+
+class TopLevel {
+    final Foo op;
+
+    TopLevel({
+        required this.op,
+    });
+
+    factory TopLevel.fromJson(Map<String, dynamic> json) => TopLevel(
+        op: Foo.fromJson(json["op"]),
+    );
+
+    Map<String, dynamic> toJson() => {
+        "op": op.toJson(),
+    };
+}
+
+class Foo {
+    final String? foo;
+    final String? bar;
+
+    Foo({
+        this.foo,
+        this.bar,
+    });
+
+    factory Foo.fromJson(Map<String, dynamic> json) => Foo(
+        foo: json["foo"],
+        bar: json["bar"],
+    );
+
+    Map<String, dynamic> toJson() => {
+        "foo": foo,
+        "bar": bar,
+    };
+}
diff --git a/head/schema-elixir/test/inputs/schema/named-class-union.schema/default/QuickType.ex b/head/schema-elixir/test/inputs/schema/named-class-union.schema/default/QuickType.ex
new file mode 100644
index 0000000..01f7e7a
--- /dev/null
+++ b/head/schema-elixir/test/inputs/schema/named-class-union.schema/default/QuickType.ex
@@ -0,0 +1,74 @@
+# This file was autogenerated using quicktype https://github.com/quicktype/quicktype
+#
+# Add Jason to your mix.exs
+#
+# Decode a JSON string: TopLevel.from_json(data)
+# Encode into a JSON string: TopLevel.to_json(struct)
+
+defmodule Foo do
+  defstruct [:foo, :bar]
+
+  @type t :: %__MODULE__{
+          foo: String.t() | nil,
+          bar: String.t() | nil
+        }
+
+  def from_map(m) do
+    %Foo{
+      foo: m["foo"],
+      bar: m["bar"],
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "foo" => struct.foo,
+      "bar" => struct.bar,
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
+
+defmodule TopLevel do
+  @enforce_keys [:op]
+  defstruct [:op]
+
+  @type t :: %__MODULE__{
+          op: Foo.t()
+        }
+
+  def from_map(m) do
+    %TopLevel{
+      op: Foo.from_map(m["op"]),
+    }
+  end
+
+  def from_json(json) do
+    json
+          |> Jason.decode!()
+          |> from_map()
+  end
+
+  def to_map(struct) do
+    %{
+      "op" => Foo.to_map(struct.op),
+    }
+  end
+
+  def to_json(struct) do
+    struct
+          |> to_map()
+          |> Jason.encode!()
+  end
+end
diff --git a/head/schema-flow/test/inputs/schema/named-class-union.schema/default/TopLevel.js b/head/schema-flow/test/inputs/schema/named-class-union.schema/default/TopLevel.js
new file mode 100644
index 0000000..d74f688
--- /dev/null
+++ b/head/schema-flow/test/inputs/schema/named-class-union.schema/default/TopLevel.js
@@ -0,0 +1,197 @@
+// @flow
+
+// To parse this data:
+//
+//   const Convert = require("./TopLevel");
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+export type TopLevel = {
+    op: Foo;
+};
+
+export type Foo = {
+    foo?: string;
+    bar?: string;
+};
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+function toTopLevel(json: string): TopLevel {
+    return cast(JSON.parse(json), r("TopLevel"));
+}
+
+function topLevelToJson(value: TopLevel): string {
+    return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+}
+
+function invalidValue(typ: any, val: any, key: any, parent: any = '') {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ: any): string {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ: any): any {
+    if (typ.jsonToJS === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ: any): any {
+    if (typ.jsToJSON === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
+    function transformPrimitive(typ: string, val: any): any {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs: any[], val: any): any {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases: string[], val: any): any {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ: any, val: any): any {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val: any): any {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result: any = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref: any = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast<T>(val: any, typ: any): T {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast<T>(val: T, typ: any): any {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ: any) {
+    return { literal: typ };
+}
+
+function a(typ: any) {
+    return { arrayItems: typ };
+}
+
+function u(...typs: any[]) {
+    return { unionMembers: typs };
+}
+
+function o(props: any[], additional: any) {
+    return { props, additional };
+}
+
+function m(additional: any) {
+    const props: any[] = [];
+    return { props, additional };
+}
+
+function r(name: string) {
+    return { ref: name };
+}
+
+const typeMap: any = {
+    "TopLevel": o([
+        { json: "op", js: "op", typ: r("Foo") },
+    ], false),
+    "Foo": o([
+        { json: "foo", js: "foo", typ: u(undefined, "") },
+        { json: "bar", js: "bar", typ: u(undefined, "") },
+    ], false),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/head/schema-golang/test/inputs/schema/named-class-union.schema/default/quicktype.go b/head/schema-golang/test/inputs/schema/named-class-union.schema/default/quicktype.go
new file mode 100644
index 0000000..1fd75fc
--- /dev/null
+++ b/head/schema-golang/test/inputs/schema/named-class-union.schema/default/quicktype.go
@@ -0,0 +1,28 @@
+// Code generated from JSON Schema using quicktype. DO NOT EDIT.
+// To parse and unparse this JSON data, add this code to your project and do:
+//
+//    topLevel, err := UnmarshalTopLevel(bytes)
+//    bytes, err = topLevel.Marshal()
+
+package main
+
+import "encoding/json"
+
+func UnmarshalTopLevel(data []byte) (TopLevel, error) {
+	var r TopLevel
+	err := json.Unmarshal(data, &r)
+	return r, err
+}
+
+func (r *TopLevel) Marshal() ([]byte, error) {
+	return json.Marshal(r)
+}
+
+type TopLevel struct {
+	Op Foo `json:"op"`
+}
+
+type Foo struct {
+	Foo *string `json:"foo,omitempty"`
+	Bar *string `json:"bar,omitempty"`
+}
diff --git a/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..a8eb236
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,101 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//     com.fasterxml.jackson.datatype : jackson-datatype-jsr310   : 2.9.0
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.temporal.ChronoField;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_INSTANT)
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetDateTime parseDateTimeString(String str) {
+        return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
+    }
+
+    private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
+            .parseDefaulting(ChronoField.YEAR, 2020)
+            .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
+            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetTime parseTimeString(String str) {
+        return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
+            @Override
+            public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
new file mode 100644
index 0000000..d2d3b62
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
@@ -0,0 +1,18 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Foo {
+    private String foo;
+    private String bar;
+
+    @JsonProperty("foo")
+    public String getFoo() { return foo; }
+    @JsonProperty("foo")
+    public void setFoo(String value) { this.foo = value; }
+
+    @JsonProperty("bar")
+    public String getBar() { return bar; }
+    @JsonProperty("bar")
+    public void setBar(String value) { this.bar = value; }
+}
diff --git a/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..5b904ad
--- /dev/null
+++ b/head/schema-java/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class TopLevel {
+    private Foo op;
+
+    @JsonProperty("op")
+    public Foo getOp() { return op; }
+    @JsonProperty("op")
+    public void setOp(Foo value) { this.op = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..7d4811b
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,121 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.util.Date;
+import java.text.SimpleDateFormat;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final String[] DATE_TIME_FORMATS = {
+            "yyyy-MM-dd'T'HH:mm:ss.SX",
+            "yyyy-MM-dd'T'HH:mm:ss.S",
+            "yyyy-MM-dd'T'HH:mm:ssX",
+            "yyyy-MM-dd'T'HH:mm:ss",
+            "yyyy-MM-dd HH:mm:ss.SX",
+            "yyyy-MM-dd HH:mm:ss.S",
+            "yyyy-MM-dd HH:mm:ssX",
+            "yyyy-MM-dd HH:mm:ss",
+            "HH:mm:ss.SZ",
+            "HH:mm:ss.S",
+            "HH:mm:ssZ",
+            "HH:mm:ss",
+            "yyyy-MM-dd",
+    };
+
+    public static Date parseAllDateTimeString(String str) {
+        for (String format : DATE_TIME_FORMATS) {
+            try {
+                return new SimpleDateFormat(format).parse(str);
+            } catch (Exception ex) {
+                // Ignored
+            }
+        }
+        return null;
+    }
+
+    public static String serializeDateTime(Date datetime) {
+        return new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ").format(datetime);
+    }
+
+    public static String serializeDate(Date datetime) {
+        return new SimpleDateFormat("yyyy-MM-dd").format(datetime);
+    }
+
+    public static String serializeTime(Date datetime) {
+        return new SimpleDateFormat("hh:mm:ssZ").format(datetime);
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        module.addDeserializer(Date.class, new JsonDeserializer<Date>() {
+            @Override
+            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseAllDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
new file mode 100644
index 0000000..d2d3b62
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
@@ -0,0 +1,18 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Foo {
+    private String foo;
+    private String bar;
+
+    @JsonProperty("foo")
+    public String getFoo() { return foo; }
+    @JsonProperty("foo")
+    public void setFoo(String value) { this.foo = value; }
+
+    @JsonProperty("bar")
+    public String getBar() { return bar; }
+    @JsonProperty("bar")
+    public void setBar(String value) { this.bar = value; }
+}
diff --git a/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..5b904ad
--- /dev/null
+++ b/head/schema-java-datetime-legacy/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class TopLevel {
+    private Foo op;
+
+    @JsonProperty("op")
+    public Foo getOp() { return op; }
+    @JsonProperty("op")
+    public void setOp(Foo value) { this.op = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
new file mode 100644
index 0000000..a8eb236
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Converter.java
@@ -0,0 +1,101 @@
+// To use this code, add the following Maven dependency to your project:
+//
+//
+//     com.fasterxml.jackson.core     : jackson-databind          : 2.9.0
+//     com.fasterxml.jackson.datatype : jackson-datatype-jsr310   : 2.9.0
+//
+// Import this package:
+//
+//     import io.quicktype.Converter;
+//
+// Then you can deserialize a JSON string with
+//
+//     TopLevel data = Converter.fromJsonString(jsonString);
+
+package io.quicktype;
+
+import java.io.IOException;
+import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.*;
+import java.time.LocalDate;
+import java.time.OffsetDateTime;
+import java.time.OffsetTime;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.temporal.ChronoField;
+
+public class Converter {
+    // Date-time helpers
+
+    private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
+            .appendOptional(DateTimeFormatter.ISO_INSTANT)
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX"))
+            .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetDateTime parseDateTimeString(String str) {
+        return ZonedDateTime.from(Converter.DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime();
+    }
+
+    private static final DateTimeFormatter TIME_FORMATTER = new DateTimeFormatterBuilder()
+            .appendOptional(DateTimeFormatter.ISO_TIME)
+            .appendOptional(DateTimeFormatter.ISO_OFFSET_TIME)
+            .parseDefaulting(ChronoField.YEAR, 2020)
+            .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
+            .parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
+            .toFormatter()
+            .withZone(ZoneOffset.UTC);
+
+    public static OffsetTime parseTimeString(String str) {
+        return ZonedDateTime.from(Converter.TIME_FORMATTER.parse(str)).toOffsetDateTime().toOffsetTime();
+    }
+    // Serialize/deserialize helpers
+
+    public static TopLevel fromJsonString(String json) throws IOException {
+        return getObjectReader().readValue(json);
+    }
+
+    public static String toJsonString(TopLevel obj) throws JsonProcessingException {
+        return getObjectWriter().writeValueAsString(obj);
+    }
+
+    private static ObjectReader reader;
+    private static ObjectWriter writer;
+
+    private static void instantiateMapper() {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.findAndRegisterModules();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
+        SimpleModule module = new SimpleModule();
+        module.addDeserializer(OffsetDateTime.class, new JsonDeserializer<OffsetDateTime>() {
+            @Override
+            public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
+                String value = jsonParser.getText();
+                return Converter.parseDateTimeString(value);
+            }
+        });
+        mapper.registerModule(module);
+        reader = mapper.readerFor(TopLevel.class);
+        writer = mapper.writerFor(TopLevel.class);
+    }
+
+    private static ObjectReader getObjectReader() {
+        if (reader == null) instantiateMapper();
+        return reader;
+    }
+
+    private static ObjectWriter getObjectWriter() {
+        if (writer == null) instantiateMapper();
+        return writer;
+    }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
new file mode 100644
index 0000000..d2d3b62
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/Foo.java
@@ -0,0 +1,18 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class Foo {
+    private String foo;
+    private String bar;
+
+    @JsonProperty("foo")
+    public String getFoo() { return foo; }
+    @JsonProperty("foo")
+    public void setFoo(String value) { this.foo = value; }
+
+    @JsonProperty("bar")
+    public String getBar() { return bar; }
+    @JsonProperty("bar")
+    public void setBar(String value) { this.bar = value; }
+}
diff --git a/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
new file mode 100644
index 0000000..5b904ad
--- /dev/null
+++ b/head/schema-java-lombok/test/inputs/schema/named-class-union.schema/default/src/main/java/io/quicktype/TopLevel.java
@@ -0,0 +1,12 @@
+package io.quicktype;
+
+import com.fasterxml.jackson.annotation.*;
+
+public class TopLevel {
+    private Foo op;
+
+    @JsonProperty("op")
+    public Foo getOp() { return op; }
+    @JsonProperty("op")
+    public void setOp(Foo value) { this.op = value; }
+}
diff --git a/head/schema-javascript/test/inputs/schema/named-class-union.schema/default/TopLevel.js b/head/schema-javascript/test/inputs/schema/named-class-union.schema/default/TopLevel.js
new file mode 100644
index 0000000..ff72b26
--- /dev/null
+++ b/head/schema-javascript/test/inputs/schema/named-class-union.schema/default/TopLevel.js
@@ -0,0 +1,186 @@
+// To parse this data:
+//
+//   const Convert = require("./TopLevel");
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+function toTopLevel(json) {
+    return cast(JSON.parse(json), r("TopLevel"));
+}
+
+function topLevelToJson(value) {
+    return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+}
+
+function invalidValue(typ, val, key, parent = '') {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ) {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ) {
+    if (typ.jsonToJS === undefined) {
+        const map = {};
+        typ.props.forEach((p) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ) {
+    if (typ.jsToJSON === undefined) {
+        const map = {};
+        typ.props.forEach((p) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val, typ, getProps, key = '', parent = '') {
+    function transformPrimitive(typ, val) {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs, val) {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases, val) {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ, val) {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val) {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props, additional, val) {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast(val, typ) {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast(val, typ) {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ) {
+    return { literal: typ };
+}
+
+function a(typ) {
+    return { arrayItems: typ };
+}
+
+function u(...typs) {
+    return { unionMembers: typs };
+}
+
+function o(props, additional) {
+    return { props, additional };
+}
+
+function m(additional) {
+    const props = [];
+    return { props, additional };
+}
+
+function r(name) {
+    return { ref: name };
+}
+
+const typeMap = {
+    "TopLevel": o([
+        { json: "op", js: "op", typ: r("Foo") },
+    ], false),
+    "Foo": o([
+        { json: "foo", js: "foo", typ: u(undefined, "") },
+        { json: "bar", js: "bar", typ: u(undefined, "") },
+    ], false),
+};
+
+module.exports = {
+    "topLevelToJson": topLevelToJson,
+    "toTopLevel": toTopLevel,
+};
diff --git a/head/schema-kotlinx/test/inputs/schema/named-class-union.schema/default/TopLevel.kt b/head/schema-kotlinx/test/inputs/schema/named-class-union.schema/default/TopLevel.kt
new file mode 100644
index 0000000..eac0b37
--- /dev/null
+++ b/head/schema-kotlinx/test/inputs/schema/named-class-union.schema/default/TopLevel.kt
@@ -0,0 +1,22 @@
+// To parse the JSON, install kotlin's serialization plugin and do:
+//
+// val json     = Json { allowStructuredMapKeys = true }
+// val topLevel = json.parse(TopLevel.serializer(), jsonString)
+
+package quicktype
+
+import kotlinx.serialization.*
+import kotlinx.serialization.json.*
+import kotlinx.serialization.descriptors.*
+import kotlinx.serialization.encoding.*
+
+@Serializable
+data class TopLevel (
+    val op: Foo
+)
+
+@Serializable
+data class Foo (
+    val foo: String? = null,
+    val bar: String? = null
+)
diff --git a/head/schema-php/test/inputs/schema/named-class-union.schema/default/TopLevel.php b/head/schema-php/test/inputs/schema/named-class-union.schema/default/TopLevel.php
new file mode 100644
index 0000000..833bd5f
--- /dev/null
+++ b/head/schema-php/test/inputs/schema/named-class-union.schema/default/TopLevel.php
@@ -0,0 +1,273 @@
+<?php
+declare(strict_types=1);
+
+// This is an autogenerated file:TopLevel
+
+class TopLevel {
+    private Foo $op; // json:op Required
+
+    /**
+     * @param Foo $op
+     */
+    public function __construct(Foo $op) {
+        $this->op = $op;
+    }
+
+    /**
+     * @param stdClass $value
+     * @throws Exception
+     * @return Foo
+     */
+    public static function fromOp(stdClass $value): Foo {
+        return Foo::from($value); /*class*/
+    }
+
+    /**
+     * @throws Exception
+     * @return stdClass
+     */
+    public function toOp(): stdClass {
+        if (TopLevel::validateOp($this->op))  {
+            return $this->op->to(); /*class*/
+        }
+        throw new Exception('never get to this TopLevel::op');
+    }
+
+    /**
+     * @param Foo
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateOp(Foo $value): bool {
+        $value->validate();
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return Foo
+     */
+    public function getOp(): Foo {
+        if (TopLevel::validateOp($this->op))  {
+            return $this->op;
+        }
+        throw new Exception('never get to getOp TopLevel::op');
+    }
+
+    /**
+     * @return Foo
+     */
+    public static function sampleOp(): Foo {
+        return Foo::sample(); /*31:op*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return TopLevel::validateOp($this->op);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'op'} = $this->toOp();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return TopLevel
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): TopLevel {
+        return new TopLevel(
+         TopLevel::fromOp($obj->{'op'})
+        );
+    }
+
+    /**
+     * @return TopLevel
+     */
+    public static function sample(): TopLevel {
+        return new TopLevel(
+         TopLevel::sampleOp()
+        );
+    }
+}
+
+// This is an autogenerated file:Foo
+
+class Foo {
+    private ?string $foo; // json:foo Optional
+    private ?string $bar; // json:bar Optional
+
+    /**
+     * @param string|null $foo
+     * @param string|null $bar
+     */
+    public function __construct(?string $foo, ?string $bar) {
+        $this->foo = $foo;
+        $this->bar = $bar;
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromFoo(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toFoo(): ?string {
+        if (Foo::validateFoo($this->foo))  {
+            if (!is_null($this->foo)) {
+                return $this->foo; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this Foo::foo');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateFoo(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getFoo(): ?string {
+        if (Foo::validateFoo($this->foo))  {
+            return $this->foo;
+        }
+        throw new Exception('never get to getFoo Foo::foo');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleFoo(): ?string {
+        return 'Foo::foo::31'; /*31:foo*/
+    }
+
+    /**
+     * @param ?string $value
+     * @throws Exception
+     * @return ?string
+     */
+    public static function fromBar(?string $value): ?string {
+        if (!is_null($value)) {
+            return $value; /*string*/
+        } else {
+            return  null;
+        }
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function toBar(): ?string {
+        if (Foo::validateBar($this->bar))  {
+            if (!is_null($this->bar)) {
+                return $this->bar; /*string*/
+            } else {
+                return  null;
+            }
+        }
+        throw new Exception('never get to this Foo::bar');
+    }
+
+    /**
+     * @param string|null
+     * @return bool
+     * @throws Exception
+     */
+    public static function validateBar(?string $value): bool {
+        if (!is_null($value)) {
+        }
+        return true;
+    }
+
+    /**
+     * @throws Exception
+     * @return ?string
+     */
+    public function getBar(): ?string {
+        if (Foo::validateBar($this->bar))  {
+            return $this->bar;
+        }
+        throw new Exception('never get to getBar Foo::bar');
+    }
+
+    /**
+     * @return ?string
+     */
+    public static function sampleBar(): ?string {
+        return 'Foo::bar::32'; /*32:bar*/
+    }
+
+    /**
+     * @throws Exception
+     * @return bool
+     */
+    public function validate(): bool {
+        return Foo::validateFoo($this->foo)
+        || Foo::validateBar($this->bar);
+    }
+
+    /**
+     * @return stdClass
+     * @throws Exception
+     */
+    public function to(): stdClass  {
+        $out = new stdClass();
+        $out->{'foo'} = $this->toFoo();
+        $out->{'bar'} = $this->toBar();
+        return $out;
+    }
+
+    /**
+     * @param stdClass $obj
+     * @return Foo
+     * @throws Exception
+     */
+    public static function from(stdClass $obj): Foo {
+        return new Foo(
+         Foo::fromFoo($obj->{'foo'})
+        ,Foo::fromBar($obj->{'bar'})
+        );
+    }
+
+    /**
+     * @return Foo
+     */
+    public static function sample(): Foo {
+        return new Foo(
+         Foo::sampleFoo()
+        ,Foo::sampleBar()
+        );
+    }
+}
diff --git a/head/schema-pike/test/inputs/schema/named-class-union.schema/default/TopLevel.pmod b/head/schema-pike/test/inputs/schema/named-class-union.schema/default/TopLevel.pmod
new file mode 100644
index 0000000..8330c8c
--- /dev/null
+++ b/head/schema-pike/test/inputs/schema/named-class-union.schema/default/TopLevel.pmod
@@ -0,0 +1,56 @@
+// This source has been automatically generated by quicktype.
+// ( https://github.com/quicktype/quicktype )
+//
+// To use this code, simply import it into your project as a Pike module.
+// To JSON-encode your object, you can pass it to `Standards.JSON.encode`
+// or call `encode_json` on it.
+//
+// To decode a JSON string, first pass it to `Standards.JSON.decode`,
+// and then pass the result to `<YourClass>_from_JSON`.
+// It will return an instance of <YourClass>.
+// Bear in mind that these functions have unexpected behavior,
+// and will likely throw an error, if the JSON string does not
+// match the expected interface, even if the JSON itself is valid.
+
+class TopLevel {
+    Foo op; // json: "op"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "op" : op,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+TopLevel TopLevel_from_JSON(mixed json) {
+    TopLevel retval = TopLevel();
+
+    retval.op = json["op"];
+
+    return retval;
+}
+
+class Foo {
+    mixed|string foo; // json: "foo"
+    mixed|string bar; // json: "bar"
+
+    string encode_json() {
+        mapping(string:mixed) json = ([
+            "foo" : foo,
+            "bar" : bar,
+        ]);
+
+        return Standards.JSON.encode(json);
+    }
+}
+
+Foo Foo_from_JSON(mixed json) {
+    Foo retval = Foo();
+
+    retval.foo = json["foo"];
+    retval.bar = json["bar"];
+
+    return retval;
+}
diff --git a/head/schema-python/test/inputs/schema/named-class-union.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/named-class-union.schema/default/quicktype.py
new file mode 100644
index 0000000..8d56a40
--- /dev/null
+++ b/head/schema-python/test/inputs/schema/named-class-union.schema/default/quicktype.py
@@ -0,0 +1,80 @@
+from dataclasses import dataclass
+from typing import Any, TypeVar, Type, cast
+
+
+T = TypeVar("T")
+
+
+def from_str(x: Any) -> str:
+    assert isinstance(x, str)
+    return x
+
+
+def from_union(fs, x):
+    for f in fs:
+        try:
+            return f(x)
+        except:
+            pass
+    assert False
+
+
+def to_class(c: Type[T], x: Any) -> dict:
+    assert isinstance(x, c)
+    return cast(Any, x).to_dict()
+
+
+@dataclass
+class Foo:
+    foo: str
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'Foo':
+        assert isinstance(obj, dict)
+        foo = from_str(obj.get("foo"))
+        return Foo(foo)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        result["foo"] = from_str(self.foo)
+        return result
+
+
+@dataclass
+class Bar:
+    bar: str
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'Bar':
+        assert isinstance(obj, dict)
+        bar = from_str(obj.get("bar"))
+        return Bar(bar)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        result["bar"] = from_str(self.bar)
+        return result
+
+
+@dataclass
+class TopLevel:
+    op: Foo | Bar
+
+    @staticmethod
+    def from_dict(obj: Any) -> 'TopLevel':
+        assert isinstance(obj, dict)
+        op = from_union([Foo.from_dict, Bar.from_dict], obj.get("op"))
+        return TopLevel(op)
+
+    def to_dict(self) -> dict:
+        result: dict = {}
+        result["op"] = from_union([lambda x: to_class(Foo, x), lambda x: to_class(Bar, x)], self.op)
+        return result
+
+
+def top_level_from_dict(s: Any) -> TopLevel:
+    return TopLevel.from_dict(s)
+
+
+def top_level_to_dict(x: TopLevel) -> Any:
+    return to_class(TopLevel, x)
diff --git a/base/schema-python/test/inputs/schema/vega-lite.schema/default/quicktype.py b/head/schema-python/test/inputs/schema/vega-lite.schema/default/quicktype.py
index af71a4d..89faf1e 100644
--- a/base/schema-python/test/inputs/schema/vega-lite.schema/default/quicktype.py
+++ b/head/schema-python/test/inputs/schema/vega-lite.schema/default/quicktype.py
@@ -5332,7 +5332,7 @@ class FacetFieldDef:
 
 
 @dataclass
-class FieldDef:
+class FieldDefElement:
     """Definition object for a data field, its type and transformation of an encoding channel."""
 
     type: ConditionalPredicateValueDefType
@@ -5374,14 +5374,14 @@ class FieldDef:
     """
 
     @staticmethod
-    def from_dict(obj: Any) -> 'FieldDef':
+    def from_dict(obj: Any) -> 'FieldDefElement':
         assert isinstance(obj, dict)
         type = ConditionalPredicateValueDefType(obj.get("type"))
         aggregate = from_union([AggregateOp, from_none], obj.get("aggregate"))
         bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin"))
         field = from_union([RepeatRef.from_dict, from_str, from_none], obj.get("field"))
         time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit"))
-        return FieldDef(type, aggregate, bin, field, time_unit)
+        return FieldDefElement(type, aggregate, bin, field, time_unit)
 
     def to_dict(self) -> dict:
         result: dict = {}
@@ -6065,12 +6065,12 @@ class Axis:
 
 
 @dataclass
-class XClass:
-    """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`.
-    
-    Y coordinates of the marks, or height of vertical `"bar"` and `"area"`.
-    
-    Definition object for a constant value of an encoding channel.
+class PositionFieldDef:
+    type: ConditionalPredicateValueDefType
+    """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or
+    `"nominal"`).
+    It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a
+    [geographic projection](projection.html) is applied.
     """
     aggregate: AggregateOp | None = None
     """Aggregation function for the field
@@ -6146,20 +6146,11 @@ class XClass:
     
     __Default value:__ `undefined` (None)
     """
-    type: ConditionalPredicateValueDefType | None = None
-    """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or
-    `"nominal"`).
-    It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a
-    [geographic projection](projection.html) is applied.
-    """
-    value: float | bool | str | None = None
-    """A constant value in visual domain (e.g., `"red"` / "#0099ff" for color, values between
-    `0` to `1` for opacity).
-    """
 
     @staticmethod
-    def from_dict(obj: Any) -> 'XClass':
+    def from_dict(obj: Any) -> 'PositionFieldDef':
         assert isinstance(obj, dict)
+        type = ConditionalPredicateValueDefType(obj.get("type"))
         aggregate = from_union([AggregateOp, from_none], obj.get("aggregate"))
         axis = from_union([Axis.from_dict, from_none], obj.get("axis"))
         bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin"))
@@ -6168,12 +6159,11 @@ class XClass:
         sort = from_union([from_none, SortField.from_dict, SortEnum], obj.get("sort"))
         stack = from_union([StackOffset, from_none], obj.get("stack"))
         time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit"))
-        type = from_union([ConditionalPredicateValueDefType, from_none], obj.get("type"))
-        value = from_union([from_float, from_bool, from_str, from_none], obj.get("value"))
-        return XClass(aggregate, axis, bin, field, scale, sort, stack, time_unit, type, value)
+        return PositionFieldDef(type, aggregate, axis, bin, field, scale, sort, stack, time_unit)
 
     def to_dict(self) -> dict:
         result: dict = {}
+        result["type"] = to_enum(ConditionalPredicateValueDefType, self.type)
         if self.aggregate is not None:
             result["aggregate"] = from_union([lambda x: to_enum(AggregateOp, x), from_none], self.aggregate)
         if self.axis is not None:
@@ -6190,90 +6180,27 @@ class XClass:
             result["stack"] = from_union([lambda x: to_enum(StackOffset, x), from_none], self.stack)
         if self.time_unit is not None:
             result["timeUnit"] = from_union([lambda x: to_enum(TimeUnit, x), from_none], self.time_unit)
-        if self.type is not None:
-            result["type"] = from_union([lambda x: to_enum(ConditionalPredicateValueDefType, x), from_none], self.type)
-        if self.value is not None:
-            result["value"] = from_union([to_float, from_bool, from_str, from_none], self.value)
         return result
 
 
 @dataclass
-class X2Class:
-    """X2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`.
-    
-    Y2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`.
-    
-    Definition object for a data field, its type and transformation of an encoding channel.
-    
-    Definition object for a constant value of an encoding channel.
-    """
-    aggregate: AggregateOp | None = None
-    """Aggregation function for the field
-    (e.g., `mean`, `sum`, `median`, `min`, `max`, `count`).
-    
-    __Default value:__ `undefined` (None)
-    """
-    bin: bool | BinParams | None = None
-    """A flag for binning a `quantitative` field, or [an object defining binning
-    parameters](bin.html#params).
-    If `true`, default [binning parameters](bin.html) will be applied.
-    
-    __Default value:__ `false`
-    """
-    field: RepeatRef | str | None = None
-    """__Required.__ A string defining the name of the field from which to pull a data value
-    or an object defining iterated values from the [`repeat`](repeat.html) operator.
-    
-    __Note:__ Dots (`.`) and brackets (`[` and `]`) can be used to access nested objects
-    (e.g., `"field": "foo.bar"` and `"field": "foo['bar']"`).
-    If field names contain dots or brackets but are not nested, you can use `\\\\` to escape
-    dots and brackets (e.g., `"a\\\\.b"` and `"a\\\\[0\\\\]"`).
-    See more details about escaping in the [field documentation](field.html).
-    
-    __Note:__ `field` is not required if `aggregate` is `count`.
-    """
-    time_unit: TimeUnit | None = None
-    """Time unit (e.g., `year`, `yearmonth`, `month`, `hours`) for a temporal field.
-    or [a temporal field that gets casted as ordinal](type.html#cast).
-    
-    __Default value:__ `undefined` (None)
-    """
-    type: ConditionalPredicateValueDefType | None = None
-    """The encoded field's type of measurement (`"quantitative"`, `"temporal"`, `"ordinal"`, or
-    `"nominal"`).
-    It can also be a geo type (`"latitude"`, `"longitude"`, and `"geojson"`) when a
-    [geographic projection](projection.html) is applied.
-    """
-    value: float | bool | str | None = None
+class ValueDef:
+    """Definition object for a constant value of an encoding channel."""
+
+    value: float | bool | str
     """A constant value in visual domain (e.g., `"red"` / "#0099ff" for color, values between
     `0` to `1` for opacity).
     """
 
     @staticmethod
-    def from_dict(obj: Any) -> 'X2Class':
+    def from_dict(obj: Any) -> 'ValueDef':
         assert isinstance(obj, dict)
-        aggregate = from_union([AggregateOp, from_none], obj.get("aggregate"))
-        bin = from_union([from_bool, BinParams.from_dict, from_none], obj.get("bin"))
-        field = from_union([RepeatRef.from_dict, from_str, from_none], obj.get("field"))
-        time_unit = from_union([TimeUnit, from_none], obj.get("timeUnit"))
-        type = from_union([ConditionalPredicateValueDefType, from_none], obj.get("type"))
-        value = from_union([from_float, from_bool, from_str, from_none], obj.get("value"))
-        return X2Class(aggregate, bin, field, time_unit, type, value)
+        value = from_union([from_float, from_bool, from_str], obj.get("value"))
+        return ValueDef(value)
 
     def to_dict(self) -> dict:
         result: dict = {}
-        if self.aggregate is not None:
-            result["aggregate"] = from_union([lambda x: to_enum(AggregateOp, x), from_none], self.aggregate)
-        if self.bin is not None:
-            result["bin"] = from_union([from_bool, lambda x: to_class(BinParams, x), from_none], self.bin)
-        if self.field is not None:
-            result["field"] = from_union([lambda x: to_class(RepeatRef, x), from_str, from_none], self.field)
-        if self.time_unit is not None:
-            result["timeUnit"] = from_union([lambda x: to_enum(TimeUnit, x), from_none], self.time_unit)
-        if self.type is not None:
-            result["type"] = from_union([lambda x: to_enum(ConditionalPredicateValueDefType, x), from_none], self.type)
-        if self.value is not None:
-            result["value"] = from_union([to_float, from_bool, from_str, from_none], self.value)
+        result["value"] = from_union([to_float, from_bool, from_str], self.value)
         return result
 
 
@@ -6295,7 +6222,7 @@ class EncodingWithFacet:
     column: FacetFieldDef | None = None
     """Horizontal facets for trellis plots."""
 
-    detail: FieldDef | list[FieldDef] | None = None
+    detail: FieldDefElement | list[FieldDefElement] | None = None
     """Additional levels of detail for grouping data in aggregate views and
     in line and area marks without mapping data to a specific visual channel.
     """
@@ -6340,16 +6267,16 @@ class EncodingWithFacet:
     tooltip: TextDefWithCondition | None = None
     """The tooltip text to show upon mouse hover."""
 
-    x: XClass | None = None
+    x: PositionFieldDef | ValueDef | None = None
     """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`."""
 
-    x2: X2Class | None = None
+    x2: FieldDefElement | ValueDef | None = None
     """X2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`."""
 
-    y: XClass | None = None
+    y: PositionFieldDef | ValueDef | None = None
     """Y coordinates of the marks, or height of vertical `"bar"` and `"area"`."""
 
-    y2: X2Class | None = None
+    y2: FieldDefElement | ValueDef | None = None
     """Y2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`."""
 
     @staticmethod
@@ -6357,7 +6284,7 @@ class EncodingWithFacet:
         assert isinstance(obj, dict)
         color = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("color"))
         column = from_union([FacetFieldDef.from_dict, from_none], obj.get("column"))
-        detail = from_union([FieldDef.from_dict, lambda x: from_list(FieldDef.from_dict, x), from_none], obj.get("detail"))
+        detail = from_union([FieldDefElement.from_dict, lambda x: from_list(FieldDefElement.from_dict, x), from_none], obj.get("detail"))
         href = from_union([DefWithCondition.from_dict, from_none], obj.get("href"))
         opacity = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("opacity"))
         order = from_union([OrderFieldDef.from_dict, lambda x: from_list(OrderFieldDef.from_dict, x), from_none], obj.get("order"))
@@ -6366,10 +6293,10 @@ class EncodingWithFacet:
         size = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("size"))
         text = from_union([TextDefWithCondition.from_dict, from_none], obj.get("text"))
         tooltip = from_union([TextDefWithCondition.from_dict, from_none], obj.get("tooltip"))
-        x = from_union([XClass.from_dict, from_none], obj.get("x"))
-        x2 = from_union([X2Class.from_dict, from_none], obj.get("x2"))
-        y = from_union([XClass.from_dict, from_none], obj.get("y"))
-        y2 = from_union([X2Class.from_dict, from_none], obj.get("y2"))
+        x = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("x"))
+        x2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("x2"))
+        y = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("y"))
+        y2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("y2"))
         return EncodingWithFacet(color, column, detail, href, opacity, order, row, shape, size, text, tooltip, x, x2, y, y2)
 
     def to_dict(self) -> dict:
@@ -6379,7 +6306,7 @@ class EncodingWithFacet:
         if self.column is not None:
             result["column"] = from_union([lambda x: to_class(FacetFieldDef, x), from_none], self.column)
         if self.detail is not None:
-            result["detail"] = from_union([lambda x: to_class(FieldDef, x), lambda x: from_list(lambda x: to_class(FieldDef, x), x), from_none], self.detail)
+            result["detail"] = from_union([lambda x: to_class(FieldDefElement, x), lambda x: from_list(lambda x: to_class(FieldDefElement, x), x), from_none], self.detail)
         if self.href is not None:
             result["href"] = from_union([lambda x: to_class(DefWithCondition, x), from_none], self.href)
         if self.opacity is not None:
@@ -6397,13 +6324,13 @@ class EncodingWithFacet:
         if self.tooltip is not None:
             result["tooltip"] = from_union([lambda x: to_class(TextDefWithCondition, x), from_none], self.tooltip)
         if self.x is not None:
-            result["x"] = from_union([lambda x: to_class(XClass, x), from_none], self.x)
+            result["x"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x)
         if self.x2 is not None:
-            result["x2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.x2)
+            result["x2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x2)
         if self.y is not None:
-            result["y"] = from_union([lambda x: to_class(XClass, x), from_none], self.y)
+            result["y"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y)
         if self.y2 is not None:
-            result["y2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.y2)
+            result["y2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y2)
         return result
 
 
@@ -6449,7 +6376,7 @@ class Encoding:
     _Note:_ See the scale documentation for more information about customizing [color
     scheme](scale.html#scheme).
     """
-    detail: FieldDef | list[FieldDef] | None = None
+    detail: FieldDefElement | list[FieldDefElement] | None = None
     """Additional levels of detail for grouping data in aggregate views and
     in line and area marks without mapping data to a specific visual channel.
     """
@@ -6491,23 +6418,23 @@ class Encoding:
     tooltip: TextDefWithCondition | None = None
     """The tooltip text to show upon mouse hover."""
 
-    x: XClass | None = None
+    x: PositionFieldDef | ValueDef | None = None
     """X coordinates of the marks, or width of horizontal `"bar"` and `"area"`."""
 
-    x2: X2Class | None = None
+    x2: FieldDefElement | ValueDef | None = None
     """X2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`."""
 
-    y: XClass | None = None
+    y: PositionFieldDef | ValueDef | None = None
     """Y coordinates of the marks, or height of vertical `"bar"` and `"area"`."""
 
-    y2: X2Class | None = None
+    y2: FieldDefElement | ValueDef | None = None
     """Y2 coordinates for ranged  `"area"`, `"bar"`, `"rect"`, and  `"rule"`."""
 
     @staticmethod
     def from_dict(obj: Any) -> 'Encoding':
         assert isinstance(obj, dict)
         color = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("color"))
-        detail = from_union([FieldDef.from_dict, lambda x: from_list(FieldDef.from_dict, x), from_none], obj.get("detail"))
+        detail = from_union([FieldDefElement.from_dict, lambda x: from_list(FieldDefElement.from_dict, x), from_none], obj.get("detail"))
         href = from_union([DefWithCondition.from_dict, from_none], obj.get("href"))
         opacity = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("opacity"))
         order = from_union([OrderFieldDef.from_dict, lambda x: from_list(OrderFieldDef.from_dict, x), from_none], obj.get("order"))
@@ -6515,10 +6442,10 @@ class Encoding:
         size = from_union([MarkPropDefWithCondition.from_dict, from_none], obj.get("size"))
         text = from_union([TextDefWithCondition.from_dict, from_none], obj.get("text"))
         tooltip = from_union([TextDefWithCondition.from_dict, from_none], obj.get("tooltip"))
-        x = from_union([XClass.from_dict, from_none], obj.get("x"))
-        x2 = from_union([X2Class.from_dict, from_none], obj.get("x2"))
-        y = from_union([XClass.from_dict, from_none], obj.get("y"))
-        y2 = from_union([X2Class.from_dict, from_none], obj.get("y2"))
+        x = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("x"))
+        x2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("x2"))
+        y = from_union([lambda x: from_union([PositionFieldDef.from_dict, ValueDef.from_dict], x), from_none], obj.get("y"))
+        y2 = from_union([lambda x: from_union([FieldDefElement.from_dict, ValueDef.from_dict], x), from_none], obj.get("y2"))
         return Encoding(color, detail, href, opacity, order, shape, size, text, tooltip, x, x2, y, y2)
 
     def to_dict(self) -> dict:
@@ -6526,7 +6453,7 @@ class Encoding:
         if self.color is not None:
             result["color"] = from_union([lambda x: to_class(MarkPropDefWithCondition, x), from_none], self.color)
         if self.detail is not None:
-            result["detail"] = from_union([lambda x: to_class(FieldDef, x), lambda x: from_list(lambda x: to_class(FieldDef, x), x), from_none], self.detail)
+            result["detail"] = from_union([lambda x: to_class(FieldDefElement, x), lambda x: from_list(lambda x: to_class(FieldDefElement, x), x), from_none], self.detail)
         if self.href is not None:
             result["href"] = from_union([lambda x: to_class(DefWithCondition, x), from_none], self.href)
         if self.opacity is not None:
@@ -6542,13 +6469,13 @@ class Encoding:
         if self.tooltip is not None:
             result["tooltip"] = from_union([lambda x: to_class(TextDefWithCondition, x), from_none], self.tooltip)
         if self.x is not None:
-            result["x"] = from_union([lambda x: to_class(XClass, x), from_none], self.x)
+            result["x"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x)
         if self.x2 is not None:
-            result["x2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.x2)
+            result["x2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.x2)
         if self.y is not None:
-            result["y"] = from_union([lambda x: to_class(XClass, x), from_none], self.y)
+            result["y"] = from_union([lambda x: from_union([lambda x: to_class(PositionFieldDef, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y)
         if self.y2 is not None:
-            result["y2"] = from_union([lambda x: to_class(X2Class, x), from_none], self.y2)
+            result["y2"] = from_union([lambda x: from_union([lambda x: to_class(FieldDefElement, x), lambda x: to_class(ValueDef, x)], x), from_none], self.y2)
         return result
 
 
diff --git a/head/schema-ruby/test/inputs/schema/named-class-union.schema/default/TopLevel.rb b/head/schema-ruby/test/inputs/schema/named-class-union.schema/default/TopLevel.rb
new file mode 100644
index 0000000..6277a5d
--- /dev/null
+++ b/head/schema-ruby/test/inputs/schema/named-class-union.schema/default/TopLevel.rb
@@ -0,0 +1,73 @@
+# This code may look unusually verbose for Ruby (and it is), but
+# it performs some subtle and complex validation of JSON data.
+#
+# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do:
+#
+#   top_level = TopLevel.from_json! "{…}"
+#   puts top_level.op.foo
+#
+# If from_json! succeeds, the value returned matches the schema.
+
+require 'json'
+require 'dry-types'
+require 'dry-struct'
+
+module Types
+  include Dry.Types(default: :nominal)
+
+  Hash   = Strict::Hash
+  String = Strict::String
+end
+
+class Foo < Dry::Struct
+  attribute :foo, Types::String.optional
+  attribute :bar, Types::String.optional
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      foo: d["foo"],
+      bar: d["bar"],
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "foo" => foo,
+      "bar" => bar,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
+
+class TopLevel < Dry::Struct
+  attribute :op, Foo
+
+  def self.from_dynamic!(d)
+    d = Types::Hash[d]
+    new(
+      op: Foo.from_dynamic!(d.fetch("op")),
+    )
+  end
+
+  def self.from_json!(json)
+    from_dynamic!(JSON.parse(json))
+  end
+
+  def to_dynamic
+    {
+      "op" => op.to_dynamic,
+    }
+  end
+
+  def to_json(options = nil)
+    JSON.generate(to_dynamic, options)
+  end
+end
diff --git a/head/schema-rust/test/inputs/schema/named-class-union.schema/default/module_under_test.rs b/head/schema-rust/test/inputs/schema/named-class-union.schema/default/module_under_test.rs
new file mode 100644
index 0000000..3994407
--- /dev/null
+++ b/head/schema-rust/test/inputs/schema/named-class-union.schema/default/module_under_test.rs
@@ -0,0 +1,26 @@
+// Example code that deserializes and serializes the model.
+// extern crate serde;
+// #[macro_use]
+// extern crate serde_derive;
+// extern crate serde_json;
+//
+// use generated_module::TopLevel;
+//
+// fn main() {
+//     let json = r#"{"answer": 42}"#;
+//     let model: TopLevel = serde_json::from_str(&json).unwrap();
+// }
+
+use serde::{Serialize, Deserialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct TopLevel {
+    pub op: Foo,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Foo {
+    pub foo: Option<String>,
+
+    pub bar: Option<String>,
+}
diff --git a/head/schema-scala3/test/inputs/schema/named-class-union.schema/default/TopLevel.scala b/head/schema-scala3/test/inputs/schema/named-class-union.schema/default/TopLevel.scala
new file mode 100644
index 0000000..c024a61
--- /dev/null
+++ b/head/schema-scala3/test/inputs/schema/named-class-union.schema/default/TopLevel.scala
@@ -0,0 +1,17 @@
+package quicktype
+
+import io.circe.syntax._
+import io.circe._
+import cats.syntax.functor._
+
+// If a union has a null in, then we'll need this too... 
+type NullValue = None.type
+
+case class TopLevel (
+    val op : Foo
+) derives Encoder.AsObject, Decoder
+
+case class Foo (
+    val foo : Option[String] = None,
+    val bar : Option[String] = None
+) derives Encoder.AsObject, Decoder
diff --git a/head/schema-scala3-upickle/test/inputs/schema/named-class-union.schema/default/TopLevel.scala b/head/schema-scala3-upickle/test/inputs/schema/named-class-union.schema/default/TopLevel.scala
new file mode 100644
index 0000000..b83939b
--- /dev/null
+++ b/head/schema-scala3-upickle/test/inputs/schema/named-class-union.schema/default/TopLevel.scala
@@ -0,0 +1,75 @@
+package quicktype
+
+// Custom pickler so that missing keys and JSON nulls both read as None,
+// and None is left out when writing (upickle's default for Option is a
+// JSON array).
+object OptionPickler extends upickle.AttributeTagged:
+    import upickle.default.Writer
+    import upickle.default.Reader
+    override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
+        implicitly[Writer[T]].comap[Option[T]] {
+            case None => null.asInstanceOf[T]
+            case Some(x) => x
+        }
+
+    override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
+        new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
+        override def visitNull(index: Int) = None
+        }
+    }
+end OptionPickler
+
+// If a union has a null in, then we'll need this too...
+type NullValue = None.type
+given OptionPickler.ReadWriter[NullValue] = OptionPickler.readwriter[ujson.Value].bimap[NullValue](
+    _ => ujson.Null,
+    json => if json.isNull then None else throw new upickle.core.Abort("not null")
+)
+
+object JsonExt:
+    val valueReader = OptionPickler.readwriter[ujson.Value]
+
+    // upickle's built-in primitive readers are lenient -- the numeric and
+    // boolean readers accept strings, and the string reader accepts
+    // numbers and booleans -- so untagged unions need strict readers to
+    // pick the right member.
+    val strictString: OptionPickler.Reader[String] = valueReader.map {
+        case ujson.Str(s) => s
+        case json => throw new upickle.core.Abort("expected string, got " + json)
+    }
+    val strictLong: OptionPickler.Reader[Long] = valueReader.map {
+        case ujson.Num(n) if n.isWhole => n.toLong
+        case json => throw new upickle.core.Abort("expected integer, got " + json)
+    }
+    val strictDouble: OptionPickler.Reader[Double] = valueReader.map {
+        case ujson.Num(n) => n
+        case json => throw new upickle.core.Abort("expected number, got " + json)
+    }
+    val strictBoolean: OptionPickler.Reader[Boolean] = valueReader.map {
+        case ujson.Bool(b) => b
+        case json => throw new upickle.core.Abort("expected boolean, got " + json)
+    }
+
+    def badMerge[T](r1: => OptionPickler.Reader[?], rest: OptionPickler.Reader[?]*): OptionPickler.Reader[T] = valueReader.map { json =>
+        var t: T | Null = null
+        val stack       = Vector.newBuilder[Throwable]
+        (r1 +: rest).foreach { reader =>
+            if t == null then
+            try
+                t = OptionPickler.read[T](json, trace = true)(using reader.asInstanceOf[OptionPickler.Reader[T]])
+            catch
+                case exc => stack += exc
+        }
+        if t != null then t.nn else throw new Exception(json.toString(), stack.result().headOption.getOrElse(null))
+    }
+end JsonExt
+
+
+case class TopLevel (
+    val op : Foo
+) derives OptionPickler.ReadWriter
+
+case class Foo (
+    val foo : Option[String] = None,
+    val bar : Option[String] = None
+) derives OptionPickler.ReadWriter
diff --git a/head/schema-schema/test/inputs/schema/named-class-union.schema/default/TopLevel.schema b/head/schema-schema/test/inputs/schema/named-class-union.schema/default/TopLevel.schema
new file mode 100644
index 0000000..15f24c2
--- /dev/null
+++ b/head/schema-schema/test/inputs/schema/named-class-union.schema/default/TopLevel.schema
@@ -0,0 +1,33 @@
+{
+    "$schema": "http://json-schema.org/draft-06/schema#",
+    "$ref": "#/definitions/TopLevel",
+    "definitions": {
+        "TopLevel": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "op": {
+                    "$ref": "#/definitions/Foo"
+                }
+            },
+            "required": [
+                "op"
+            ],
+            "title": "TopLevel"
+        },
+        "Foo": {
+            "type": "object",
+            "additionalProperties": false,
+            "properties": {
+                "foo": {
+                    "type": "string"
+                },
+                "bar": {
+                    "type": "string"
+                }
+            },
+            "required": [],
+            "title": "Foo"
+        }
+    }
+}
diff --git a/head/schema-swift/test/inputs/schema/named-class-union.schema/default/quicktype.swift b/head/schema-swift/test/inputs/schema/named-class-union.schema/default/quicktype.swift
new file mode 100644
index 0000000..5167219
--- /dev/null
+++ b/head/schema-swift/test/inputs/schema/named-class-union.schema/default/quicktype.swift
@@ -0,0 +1,134 @@
+// This file was generated from JSON Schema using quicktype, do not modify it directly.
+// To parse the JSON, add this file to your project and do:
+//
+//   let topLevel = try TopLevel(json)
+
+import Foundation
+
+// MARK: - TopLevel
+struct TopLevel: Codable {
+    let op: Foo
+
+    enum CodingKeys: String, CodingKey {
+        case op = "op"
+    }
+}
+
+// MARK: TopLevel convenience initializers and mutators
+
+extension TopLevel {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(TopLevel.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        op: Foo? = nil
+    ) -> TopLevel {
+        return TopLevel(
+            op: op ?? self.op
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+// MARK: - Foo
+struct Foo: Codable {
+    let foo: String?
+    let bar: String?
+
+    enum CodingKeys: String, CodingKey {
+        case foo = "foo"
+        case bar = "bar"
+    }
+}
+
+// MARK: Foo convenience initializers and mutators
+
+extension Foo {
+    init(data: Data) throws {
+        self = try newJSONDecoder().decode(Foo.self, from: data)
+    }
+
+    init(_ json: String, using encoding: String.Encoding = .utf8) throws {
+        guard let data = json.data(using: encoding) else {
+            throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
+        }
+        try self.init(data: data)
+    }
+
+    init(fromURL url: URL) throws {
+        try self.init(data: try Data(contentsOf: url))
+    }
+
+    func with(
+        foo: String?? = nil,
+        bar: String?? = nil
+    ) -> Foo {
+        return Foo(
+            foo: foo ?? self.foo,
+            bar: bar ?? self.bar
+        )
+    }
+
+    func jsonData() throws -> Data {
+        return try newJSONEncoder().encode(self)
+    }
+
+    func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
+        return String(data: try self.jsonData(), encoding: encoding)
+    }
+}
+
+// MARK: - Helper functions for creating encoders and decoders
+
+func newJSONDecoder() -> JSONDecoder {
+    let decoder = JSONDecoder()
+    decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in
+        let container = try decoder.singleValueContainer()
+        let dateStr = try container.decode(String.self)
+
+        let formatter = DateFormatter()
+        formatter.calendar = Calendar(identifier: .iso8601)
+        formatter.locale = Locale(identifier: "en_US_POSIX")
+        formatter.timeZone = TimeZone(secondsFromGMT: 0)
+        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
+        if let date = formatter.date(from: dateStr) {
+            return date
+        }
+        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
+        if let date = formatter.date(from: dateStr) {
+            return date
+        }
+        throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not decode date"))
+    })
+    return decoder
+}
+
+func newJSONEncoder() -> JSONEncoder {
+    let encoder = JSONEncoder()
+    let formatter = DateFormatter()
+    formatter.calendar = Calendar(identifier: .iso8601)
+    formatter.locale = Locale(identifier: "en_US_POSIX")
+    formatter.timeZone = TimeZone(secondsFromGMT: 0)
+    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
+    encoder.dateEncodingStrategy = .formatted(formatter)
+    return encoder
+}
diff --git a/head/schema-typescript/test/inputs/schema/named-class-union.schema/default/TopLevel.ts b/head/schema-typescript/test/inputs/schema/named-class-union.schema/default/TopLevel.ts
new file mode 100644
index 0000000..f3bb444
--- /dev/null
+++ b/head/schema-typescript/test/inputs/schema/named-class-union.schema/default/TopLevel.ts
@@ -0,0 +1,192 @@
+// To parse this data:
+//
+//   import { Convert, TopLevel } from "./TopLevel";
+//
+//   const topLevel = Convert.toTopLevel(json);
+//
+// These functions will throw an error if the JSON doesn't
+// match the expected interface, even if the JSON is valid.
+
+export interface TopLevel {
+    op: Foo;
+}
+
+export interface Foo {
+    foo?: string;
+    bar?: string;
+}
+
+// Converts JSON strings to/from your types
+// and asserts the results of JSON.parse at runtime
+export class Convert {
+    public static toTopLevel(json: string): TopLevel {
+        return cast(JSON.parse(json), r("TopLevel"));
+    }
+
+    public static topLevelToJson(value: TopLevel): string {
+        return JSON.stringify(uncast(value, r("TopLevel")), null, 2);
+    }
+}
+
+function invalidValue(typ: any, val: any, key: any, parent: any = ''): never {
+    const prettyTyp = prettyTypeName(typ);
+    const parentText = parent ? ` on ${parent}` : '';
+    const keyText = key ? ` for key "${key}"` : '';
+    throw Error(`Invalid value${keyText}${parentText}. Expected ${prettyTyp} but got ${JSON.stringify(val)}`);
+}
+
+function prettyTypeName(typ: any): string {
+    if (Array.isArray(typ)) {
+        if (typ.length === 2 && typ[0] === undefined) {
+            return `an optional ${prettyTypeName(typ[1])}`;
+        } else {
+            return `one of [${typ.map(a => { return prettyTypeName(a); }).join(", ")}]`;
+        }
+    } else if (typeof typ === "object" && typ.literal !== undefined) {
+        return typ.literal;
+    } else {
+        return typeof typ;
+    }
+}
+
+function jsonToJSProps(typ: any): any {
+    if (typ.jsonToJS === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.json] = { key: p.js, typ: p.typ });
+        typ.jsonToJS = map;
+    }
+    return typ.jsonToJS;
+}
+
+function jsToJSONProps(typ: any): any {
+    if (typ.jsToJSON === undefined) {
+        const map: any = {};
+        typ.props.forEach((p: any) => map[p.js] = { key: p.json, typ: p.typ });
+        typ.jsToJSON = map;
+    }
+    return typ.jsToJSON;
+}
+
+function transform(val: any, typ: any, getProps: any, key: any = '', parent: any = ''): any {
+    function transformPrimitive(typ: string, val: any): any {
+        if (typeof typ === typeof val) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+
+    function transformUnion(typs: any[], val: any): any {
+        // val must validate against one typ in typs
+        const l = typs.length;
+        for (let i = 0; i < l; i++) {
+            const typ = typs[i];
+            try {
+                return transform(val, typ, getProps);
+            } catch (_) {}
+        }
+        return invalidValue(typs, val, key, parent);
+    }
+
+    function transformEnum(cases: string[], val: any): any {
+        if (cases.indexOf(val) !== -1) return val;
+        return invalidValue(cases.map(a => { return l(a); }), val, key, parent);
+    }
+
+    function transformArray(typ: any, val: any): any {
+        // val must be an array with no invalid elements
+        if (!Array.isArray(val)) return invalidValue(l("array"), val, key, parent);
+        return val.map(el => transform(el, typ, getProps));
+    }
+
+    function transformDate(val: any): any {
+        if (val === null) {
+            return null;
+        }
+        const d = new Date(val);
+        if (isNaN(d.valueOf())) {
+            return invalidValue(l("Date"), val, key, parent);
+        }
+        return d;
+    }
+
+    function transformObject(props: { [k: string]: any }, additional: any, val: any): any {
+        if (val === null || typeof val !== "object" || Array.isArray(val)) {
+            return invalidValue(l(ref || "object"), val, key, parent);
+        }
+        const result: any = {};
+        Object.getOwnPropertyNames(props).forEach(key => {
+            const prop = props[key];
+            const v = Object.prototype.hasOwnProperty.call(val, key) ? val[key] : undefined;
+            result[prop.key] = transform(v, prop.typ, getProps, key, ref);
+        });
+        Object.getOwnPropertyNames(val).forEach(key => {
+            if (!Object.prototype.hasOwnProperty.call(props, key)) {
+                result[key] = transform(val[key], additional, getProps, key, ref);
+            }
+        });
+        return result;
+    }
+
+    if (typ === "any") return val;
+    if (typ === null) {
+        if (val === null) return val;
+        return invalidValue(typ, val, key, parent);
+    }
+    if (typ === false) return invalidValue(typ, val, key, parent);
+    let ref: any = undefined;
+    while (typeof typ === "object" && typ.ref !== undefined) {
+        ref = typ.ref;
+        typ = typeMap[typ.ref];
+    }
+    if (Array.isArray(typ)) return transformEnum(typ, val);
+    if (typeof typ === "object") {
+        return typ.hasOwnProperty("unionMembers") ? transformUnion(typ.unionMembers, val)
+            : typ.hasOwnProperty("arrayItems")    ? transformArray(typ.arrayItems, val)
+            : typ.hasOwnProperty("props")         ? transformObject(getProps(typ), typ.additional, val)
+            : invalidValue(typ, val, key, parent);
+    }
+    // Numbers can be parsed by Date but shouldn't be.
+    if (typ === Date && typeof val !== "number") return transformDate(val);
+    return transformPrimitive(typ, val);
+}
+
+function cast<T>(val: any, typ: any): T {
+    return transform(val, typ, jsonToJSProps);
+}
+
+function uncast<T>(val: T, typ: any): any {
+    return transform(val, typ, jsToJSONProps);
+}
+
+function l(typ: any) {
+    return { literal: typ };
+}
+
+function a(typ: any) {
+    return { arrayItems: typ };
+}
+
+function u(...typs: any[]) {
+    return { unionMembers: typs };
+}
+
+function o(props: any[], additional: any) {
+    return { props, additional };
+}
+
+function m(additional: any) {
+    const props: any[] = [];
+    return { props, additional };
+}
+
+function r(name: string) {
+    return { ref: name };
+}
+
+const typeMap: any = {
+    "TopLevel": o([
+        { json: "op", js: "op", typ: r("Foo") },
+    ], false),
+    "Foo": o([
+        { json: "foo", js: "foo", typ: u(undefined, "") },
+        { json: "bar", js: "bar", typ: u(undefined, "") },
+    ], false),
+};
diff --git a/head/schema-typescript-zod/test/inputs/schema/named-class-union.schema/default/TopLevel.ts b/head/schema-typescript-zod/test/inputs/schema/named-class-union.schema/default/TopLevel.ts
new file mode 100644
index 0000000..7ba92b5
--- /dev/null
+++ b/head/schema-typescript-zod/test/inputs/schema/named-class-union.schema/default/TopLevel.ts
@@ -0,0 +1,13 @@
+import * as z from "zod";
+
+
+export const FooSchema = z.object({
+    "foo": z.string().optional(),
+    "bar": z.string().optional(),
+});
+export type Foo = z.infer<typeof FooSchema>;
+
+export const TopLevelSchema = z.object({
+    "op": FooSchema,
+});
+export type TopLevel = z.infer<typeof TopLevelSchema>;
