Add methods to types
For easier maintenance and encapsulate add custom methods.
type CustomMethods {
validate() {
return this.magic(this.value);
}
magic(question) {
return question == this.answer();
}
answer() {
return 42;
}
}
Do you envision this being used external to the type definition? E.g.
path /my/path {
validate() { return this instanceof CustomMethods && this.magic() == 42; }
}
Since "this" is not strongly types, it would be difficult to statically analyze what method you were calling.
However, I've been considering replacing the "instanceof" operator with:
path /my/path is CustomMethods {
validate() { return this.magic() == 42; }
}
So an exposed "method" on a type would be statically determined.
For purely local, "helper functions" an alternative is supporting scoped functions within a type or path:
type CustomMethods {
validate() {
return magic(this.value);
}
function magic(question) {
return question == answer();
}
function answer() {
return 42;
}
}
I like "is" instead of instanceof. Just don't forget about inheritance, so also ancestor methods can be invoked.
Calling answer() without this would have different behaviour than in TypeScript. I would prefer sticking to TypeScript syntax. For example what if you have answer method and global function.
Custom methods seem consistent.
Yes, the behavior of "is" with respect to validate() rules is to AND all the validate() expressions of the extended types.
I'm a fan of methods on types so long as validate methods within types only refer to global or type methods that don't access persistent data. This should be enforced at compile time. The read() and write() methods are the most appropriate place for data accesses.