Support user-defined type guard functions
We currently only support some baked-in forms of type checking for type guards -- typeof and instanceof. In many cases, users will have their own functions that can provide run-time type information.
Proposal: a new syntax, valid only in return type annotations, of the form x is T where x is a declared parameter in the signature, or this, and T is any type. This type is actually considered as boolean, but "lights up" type guards. Examples:
function isCat(a: Animal): a is Cat {
return a.name === 'kitty';
}
var x: Animal;
if(isCat(x)) {
x.meow(); // OK, x is Cat in this block
}
class Node {
isLeafNode(): this is LeafNode { throw new Error('abstract'); }
}
class ParentNode extends Node {
isLeafNode(): this is LeafNode { return false; }
}
class LeafNode extends Node {
isLeafNode(): this is LeafNode { return true; }
}
var someNode: LeafNode|ParentNode;
if(someNode.isLeafNode()) {
// someNode: LeafNode in this block
}
The forms if(userCheck([other args,] expr [, other args])) { and if(expr.userCheck([any args])) would apply the type guard to expr the same way that expr instanceof t and typeof expr === 'literal' do today.
@shelby3 can you explain more about how it could optimize away the structural check? If you need to do one thing if it's an implementation of Animal and another if it's one of Vehicle, you still need to structurally check which object it implements.
@eggers when the compiler knows that the instance was constructed within the function, then it knows at runtime it has to be of the type that was constructed, thus it doesn't need to do any runtime check for the structural type.
Also I want to add that afaics ideas for tagging the structural type (i.e. roughly a simulation for nominal type) instead of checking its structure (which I presume exist to increase performance), such as the feature that was implemented for this issue #1007, are afaics breaking structural type checking. And the feature of #1007 is even worse IMO, because it additionally breaks the internal consistency of the compiler because it relied on the human error to tell the compiler what the type of a (metadata) tag corresponds to.
Today (since I have now caught up on some sleep) I am going to be initiating+participating in a more holistic analysis of all this and tying it into the nominal typing discussion, as well as my proposal for typeclasses. I'll try to remember to cross-link from this issue discussion. I also will learn more about the adhoc tagging paradigm that has been adopted by JS frameworks and libraries. This is a learning process for me as well.
Is there a way to define a type guard that activates a type if it returns? Something that would allow you to write something like this:
try {
checkIsA(o)
// from here on o has type A
} catch(e) {
}
@nmaro it has been suggested but not implemented so far. See for example #8655, and other issues linked from there.