In a Smithy project (used for defining services and data structures in a platform-agnostic way, commonly with AWS APIs), a union annotated with @discriminated("type") means that this union uses a discriminated union pattern, where each member is identified by a discriminator property, in this case "type".
🔍 What is a Discriminated Union?
A discriminated union is a way to serialize a union such that:
- All variants are represented as a single object.
- A special property (the discriminator) indicates which member the object represents.
- The rest of the object contains the actual data.
In Smithy, when you annotate a union with @discriminated("type"), you're saying that the discriminator field is named "type".
✅ Example in Smithy
namespace example;
@discriminated("type")
union Vehicle {
car: Car
bike: Bike
}
structure Car {
wheels: integer
brand: string
}
structure Bike {
hasPedals: boolean
brand: string
}
The union Vehicle is tagged with @discriminated("type"), which means that Smithy expects JSON documents that conform to this pattern:
✅ Matching JSON Examples
A Car variant:
{
"type": "car",
"wheels": 4,
"brand": "Toyota"
}
A Bike variant:
{
"type": "bike",
"hasPedals": true,
"brand": "Giant"
}
🚫 Invalid JSON (just for contrast):
{
"car": {
"wheels": 4,
"brand": "Toyota"
}
}
The above represents the default (non-discriminated) union style in Smithy where each variant is keyed by its name. When using @discriminated, this format is incorrect.
🧠 Extra Notes
- The
@discriminated("type") annotation simplifies deserialization, especially in generated code, REST APIs, or JSON-based protocols.
- The value of the
"type" field must match the member name (e.g., "car" or "bike").
- All members of the union are flattened into a single object at the same level as the discriminator.
✅ Summary
| Feature | Description |
|---|
@discriminated | Specifies a field to determine union variant |
| Example field | type (common naming convention) |
| Serialization | Single object with "type" and variant fields |
👷 Full Example with Service (optional)
@discriminated("type")
union Vehicle {
car: Car
bike: Bike
}
structure Car {
wheels: integer
brand: string
}
structure Bike {
hasPedals: boolean
brand: string
}
@restJson
service VehicleService {
version: "2025-06-01",
operations: [RegisterVehicle]
}
operation RegisterVehicle {
input: RegisterVehicleInput,
output: RegisterVehicleOutput
}
structure RegisterVehicleInput {
vehicle: Vehicle
}
structure RegisterVehicleOutput {
message: string
}
Let me know if you'd like to see how this is used in code (e.g., TypeScript, Go, etc.), generated client/server behavior, or more advanced cases like nested discriminated unions.