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.
We currently only support some baked-in forms of type checking for type guards --
typeofandinstanceof. 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 Twherexis a declared parameter in the signature, orthis, andTis any type. This type is actually considered asboolean, but "lights up" type guards. Examples:The forms
if(userCheck([other args,] expr [, other args])) {andif(expr.userCheck([any args]))would apply the type guard toexprthe same way thatexpr instanceof tandtypeof expr === 'literal'do today.