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
Your turn
Now the checks get sharper: a hasTrait check can assert a trait’s exact
value. So it’s not enough to put some @length on CityName — it must be
min: 2, max: 50, and Age’s @range must be min: 0, max: 130.