Multiple Types
YAML Schema supports specifying multiple types for a value using an array. This allows a value to be validated against any of the specified types.
Basic Multiple Types
You can specify multiple types by providing an array of type names:
# Schema
type:
- string
- number
Valid examples:
"I'm a string"
42
Invalid examples:
null
true
an:
- arbitrarily
- nested
data: structure
The value must be either a string OR a number.
Multiple Types with Constraints
When using multiple types, constraints are applied to each type where applicable:
# Schema
type:
- string
- number
minimum: 1
minLength: 1
Valid examples:
1
"one"
Invalid examples:
0
""
In this example:
- For numbers, the
minimum: 1constraint applies, so0is invalid - For strings, the
minLength: 1constraint applies, so""is invalid
Use Cases
Multiple types are useful when:
- Accepting different representations: A value might be provided as either a string or a number
- Backward compatibility: Supporting both old and new formats
- Flexible schemas: Allowing users to choose the most convenient format
Comparison with anyOf
Multiple types (type: [string, number]) is similar to using anyOf:
# Using multiple types
type:
- string
- number
# Using anyOf
anyOf:
- type: string
- type: number
However, multiple types is more concise when you only need to specify types without additional constraints. Use anyOf when you need different constraints for each type or more complex composition.