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:
functionisCat(a: Animal): a is Cat{returna.name==='kitty';}varx: Animal;if(isCat(x)){x.meow();// OK, x is Cat in this block}classNode{isLeafNode(): this is LeafNode{thrownewError('abstract');}}classParentNodeextendsNode{isLeafNode(): this is LeafNode{returnfalse;}}classLeafNodeextendsNode{isLeafNode(): this is LeafNode{returntrue;}}varsomeNode: 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.