← all lessons

Lesson 5

Unions

Unions

A union is a tagged union (also called a discriminated or sum type): a value that is exactly one of several named variants.

It looks like a structure — each member has a name and a target — but the meaning is different. A structure holds all its members at once; a union holds one.

union Contact {
    email: String
    phone: String
}

A Contact value is either an email or a phone, never both, never neither. Generated code typically models this as a sealed type with one case per variant, so you handle each possibility explicitly.

Empty variants use Unit

Sometimes a variant carries no data — it’s just a tag. Target the prelude Unit shape:

union Contact {
    email: String
    phone: String
    none: Unit
}

Don’t mark union members @required

Since exactly one variant is always set, marking individual members @required is meaningless — the “one of” constraint is built into the union itself.

Your turn