Lesson 6
Traits
Traits
Traits are typed annotations you attach above a shape or member with
@name(...). They add metadata and constraints without changing the
structural type. You’ve already met one: @required.
Traits stack — one per line:
@documentation("A two-to-fifty character city name.")
@length(min: 2, max: 50)
@pattern("^[A-Za-z ]+$")
string CityName
Constraint traits: target matters
The two most common constraints apply to different kinds of shapes:
@length(min, max)— the size of astring,blob,list, ormap.@range(min, max)— the numeric value of a number shape.
@length(min: 1, max: 100)
string Title
@range(min: 0, max: 130)
integer Age
Applying @range to a string, or @length to an integer, is a target mismatch
the compiler rejects.
@pattern matches substrings
@pattern takes an ECMA-262 regex — but it matches anywhere in the value
unless you anchor it. Use ^...$ when you mean the whole string:
@pattern("^[A-Za-z ]+$")
string CityName
Traits on members, too
structure Person {
@required
@documentation("Display name.")
name: String
}