Straits syntax
Straits introduces the .*
operator and use traits
statement.
use traits
statement
1 | use traits * from traitSet; |
The use traits
statement is used to specify which traits are available.
use traits * from traitSet;
enables all the traits defined in traitSet
.
It applies to the current scopes and all subscopes.
.*
operator
1 2 | obj.*trait obj.*trait = ...; |
The .*
operator is used to access a trait of an object.
obj.*trait
will access the trait named trait
on obj
.
Exactly one trait named trait
must be available (thanks to an use traits
statement) in the scope where it's used: if none, or multiple different ones are available, an exception will be thrown.
If .*
is used to assign a trait, such trait (i.e. symbol
property) will be not-enumerable.
.*
requires a trait name to be statically used. A symbol
variable cannot be used as a trait: it can be accessed using []
.
.*
won't work on null
or undefined
, since .
operator can't work on them either.
@straits/utils offers some utility function to work with them: an asFreeFunction()
function to obtain a free function wrapping a trait. Such free function could have a default behavior for objects that don't implement the trait, which can be installed with implDefault()
.
@straits/babel
@straits/babel can be used to transpile the traits syntax into standard JavaScript.
Proposed enhancements
Use specific traits
The use traits
statement could support, besides *
, a list of trait names:
1 2 | use traits x, y from traitSet1; use traits z, * from traitSet2; |
This would cause looking for the explicitly listed traits in specific trait sets with higher priority: if different traits with the same name were enabled by some use traits *
statements, those would be ignored and no error would be thrown.
@straits/babel doesn't support such syntax yet.
.* for default implementations
It might be possible to have .*
automatically calling the default implementation of a trait (defined with implDefault
from @straits/utils) in case one were available.
That's not the current behavior.