When one field holds two types
An array of mixed things, a field that is a string on Monday and a number on Tuesday. What a generator does, and what you should do instead.
Sooner or later a sample looks like this:
{
"id": 7,
"value": "ok",
"items": [1, "two", { "three": 3 }]
}
Open this example in the tool →
and in another answer value is 42. One field, two types. A generator has
to say something about it, and what it says depends on the language.
What you get
TypeScript writes a union, which is exactly right:
value: string | number
items: Array<number | string | ItemClass>
Rust writes an enum with a variant for each shape, and serde picks the variant while it reads. Also right, and it forces you to handle both.
Go writes interface{}, which means "anything". The work moves to a type
switch in your code.
Java and C# write Object, with the same result.
Swift writes an enum with associated values, and the generated
Codable code tries each case in turn.
So the languages with a union in the type system describe your data. The ones without it give up and hand you a cast.
Where mixed types come from
Almost always from one of four places:
- A tagged shape that lost its tag. The API returns different objects in
one list and expects you to look at a
typefield. - An id that is sometimes a number and sometimes a string. Usually a change of mind halfway through the API's life.
- An error squeezed into the success shape.
"data": {...}normally and"data": "not found"when something failed. - A genuinely free-form field, such as a settings blob or metadata.
The first three are faults in the API. The fourth is honest, and the right answer there is different.
For a tagged shape, use the tag
If your JSON is really this:
{
"events": [
{ "type": "click", "x": 10, "y": 20 },
{ "type": "key", "code": "Enter" }
]
}
Open this example in the tool →
then the union is not object | object. It is a discriminated union, and
the type field is the discriminator. A generator sees two objects and
usually merges them into one type with everything optional:
interface Event {
type: string
x?: number
y?: number
code?: string
}
That compiles, and it is a lie. It says a click event may have a code.
Write this one by hand. It takes a minute and it is worth it:
type Event =
| { type: 'click'; x: number; y: number }
| { type: 'key'; code: string }
Now TypeScript narrows on type and will not let you read code from a
click. No generator can do this for you from a sample, because nothing in the
sample says which field is the tag. A JSON Schema can say it, with oneOf
and a const, and then the generated code is right.
For a free-form field, stop at the boundary
A settings object with keys you do not control should not become a type at
all. Let it be Record<string, unknown>, map[string]any,
dict[str, Any], serde_json::Value. Parse the part you need, where you need
it, and leave the rest alone.
The mistake is to generate a type from one sample of a free-form field. You end up with a type that describes one customer's settings, and it breaks for the second customer.
For an id that changes type, fix it at the edge
If id is sometimes 7 and sometimes "7", make it a string everywhere, as
early as possible. A union that flows through your whole program costs you a
check at every use. A conversion costs you one line, once.
What to do when you see any in generated code
Treat every any, interface{} and Object in the output as a question the
generator could not answer. There are only three honest replies:
- I know the shape: write it by hand as a union.
- It is genuinely free-form: leave it, and parse where you use it.
- The API is wrong: say so to whoever owns it, before more code depends on the mess.
Try it
Paste the mixed-array sample above into the tool and compare TypeScript, Rust
and Go side by side. The difference between a union and interface{} is the
clearest picture of what a type system buys you.
Try it on your own JSON. The generator runs in your browser. Nothing is uploaded, and nothing is stored on a server.
Open JSON to CodeRead next
Which JSON fields are optional? What a generator can and cannot know
A sample shows you what was there once. It cannot show you what is always there. Here is how to tell the difference, and what to do about it.
null in JSON — missing, empty, or unknown?
A key that is absent, a key that holds null, and a key that holds an empty string are three different things. Most bugs here come from treating them as one.
The number that does not fit — int64, bigint and decimal
A JSON number above 9007199254740992 is already wrong by the time a generator sees it. Here is why, and which type to ask for instead.