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.
The second example does not seem to scale very well :
class Node {
isLeafNode(): this is LeafNode { throw new Error('abstract'); }
isOtherNode(): this is OtherNode { throw new Error('abstract'); }
}
class ParentNode extends Node {
isLeafNode(): this is LeafNode { return false; }
isOtherNode(): this is OtherNode { return false; }
}
class OtherNode extends Node {
isLeafNode(): this is LeafNode { return false; }
isOtherNode(): this is OtherNode { return true; }
}
class LeafNode extends Node {
isLeafNode(): this is LeafNode { return true; }
isOtherNode(): this is OtherNode { return false; }
}
var someNode: LeafNode|ParentNode|OtherNode;
if(someNode.isLeafNode()) {
// someNode: LeafNode in this block
}
Furthermore, we are back with typing that is dependent on class construction while one would expect this to work with interface only for items as simple as these.
Finally, given that we are stuck with classes, we can currently encode this idiom more lightly with instanceof :
class SuperNode { }
class ParentNode extends SuperNode {
private constrain; // using dummy private to disjoint classes
}
class OtherNode extends SuperNode {
private constrain;
}
class LeafNode extends SuperNode {
private constrain;
leafNode : string;
}
var someNode : ParentNode | OtherNode | LeafNode;
if(someNode instanceof LeafNode) {
someNode.leafNode;
}
The first example seems to be an excellent case for #1003
Perhaps the second example was not clear in its intent. Consider something like this, where instanceof would not work:
interface Sortable {
sort(): void;
}
class BaseCollection {
isSortable(): this is Sortable { return false; }
}
class List extends BaseCollection implements Sortable {
isSortable(): this is Sortable { return true; }
sort() { ... }
}
class HashSet extends BaseCollection {
isSortable(): this is Sortable { return false; }
}
class LinkedList extends BaseCollection implements Sortable {
isSortable(): this is Sortable { return true; }
sort() { ... }
}
Indeed its intent is indeed clearer. So I have two comments :
- With the current compiler, we can leverage that everything is either "undefined" or something to create an optional conversion :
interface Sortable {
sort(): void;
}
class BaseCollection {
asSortable() : Sortable { return undefined }
}
class List extends BaseCollection implements Sortable {
asSortable() { return this }
sort(){}
}
class HashSet extends BaseCollection {
}
class LinkedList extends BaseCollection implements Sortable {
asSortable() { return this; }
sort() { }
}
function someFun(collection : BaseCollection) {
var asSortable = collection.asSortable();
if(asSortable) {
asSortable.sort();
}
}
But I agree that it would be strange to do something through asSortable and then come back on collection to call other methods.
- I assume that the compiler verifies that the result of "this is Sortable" is in accordance with what the class actually implements (the verification might be done structurally). In that case, what about generating the "return true" ?
class List extends BaseCollection implements Sortable {
isSortable() : this is Sortable; // would return true
sort() { ... }
}
class OtherList extends BaseCollection {
isSortable() : this is Sortable; // would return true
sort() { ... }
}
class OtherList2 extends BaseCollection {
isSortable() : this is Sortable; // would return false
}
class OtherList3 {
isSortable() : this is Sortable; // would return true
sort() { ... }
}
class OtherList4 {
isSortable() : this is Sortable; // would return false
}
This is a cool idea. Have you considered combining it with generics? Then you could do something like this for array checks:
function isNumber(nbr): nbr is number {
return typeof nbr === 'number';
}
function isString(str): str is string {
return typeof str === 'string';
}
function isArrayOf<T>(of: (item) => item is T, a: any[]): a is T[] {
// Ensure that there's at least one item of T in the array, and all others are of T too.
}
function isArrayOrEmptyOf<T>(of: (item) => item is T, a: any[]): a is T[] {
// Accepts an empty array, or where all items are of T.
}
function(input: string|string[]|number[]) {
if (isString(input)) {
// It's a string.
}
else if (isArrayOrEmptyOf(isString, input)) {
// It's an array of string, or
// an empty array (could be either of string or number!)
}
else if (isArrayOf(isNumber, input)) {
// It's an array of number.
}
}
@bgever We did indeed consider that. It breaks down to (a) allowing x is T where T is a type parameter, and (b) extending type inference such that a type argument can be inferred from the target type of a user defined type guard function. All up I think this could be really useful.
One example usage for the standard library - Array.isArray can be changed to:
interface ArrayConstructor {
isArray<T>(arg: any): arg is T[];
}
@Arnavion I believe that for Array.isArray it would be more correct to express in a non-generic way:
interface ArrayConstructor {
isArray(arg: any): arg is any[];
}
This would support union types like MyCustomObject | any[]
And how about:
interface Object {
hasOwnProperty<T | any>(v: string): v is T;
}
Object.hasOwnProperty<MyCustomObject>.call(obj, 'id');
Or it could narrow to possible matching types obj could be:
var obj: { id: number; description: string; } | any;
if ('id' in obj) {
// obj.id is valid here
}
@awerlang
Actually, I suppose isArray<T>(): T[] would give the false assurance that the array only has elements of type T. It might be better to require the user to give an explicit assertion <T[]> so that they know they have to perform some validation after the call to isArray to be sure they actually have a T[].
Your last example results in obj being of type any because of union type behavior, so obj.id is also allowed already. If you meant you wanted obj to be considered of the first type in the union (and thus obj.id would have type number) inside the if block, then that doesn't seem right. obj could be { id: "foo" } which would not be assignable to the first type.
For your second example, I assume you meant hasOwnProperty<T>(obj: T | any, v: string): obj is T;. This has the same problem - the presence of an 'id' member doesn't really tell you that obj is of MyCustomObject type and not some other type that also has an id property. So it should be something like hasOwnProperty(obj: any, v: string): obj is { [v]: any };.
Even if the obj was of type { id: number, description: string } | { foo: string } (i.e., the union doesn't contain any), the second and third example should still result in obj being of type { id: any } inside the if-block, because obj could actually be { foo: "5", id: "bar" } which isn't assignable to the first type but is assignable to the second.
@Arnavion
I think having isArray(arg): arg is any[] is convenient, even though we don't assert element type.
About inferring an object type by duck-typing, I consider it is not a problem in its own, although I see the problems it may lead to. This is a concern in #1427 . How would you handle this?
Sorry, perhaps I wasn't clear. I was agreeing with you that isArray should return arg is any[].
And yes, #1427 is exactly the same as what I said for your other two examples.
Here's another use case based on a filesystem Entry as defined in the not-yet-standard File System API:
interface Entry {
isFile: boolean;
isDirectory: boolean;
name: string;
...
}
interface DirectoryEntry extends Entry { ... }
interface FileEntry extends Entry { ... }
When (<Entry>entry).isFile, entry is a FileEntry, and when entry.isDirectory, entry is a DirectoryEntry.
Note that the *Entry classes are not easily accessible, so instanceof can't be used.
Approved; assignment to Anders is tentative (someone else can give this a shot if they're feeling up to the challenge)
@RyanCavanaugh I decided to take shot on this. Just one question. Can the type guard function take multiple arguments?
function isCat(a: Animal, b: number): a is Cat {
return a.name === 'kitty';
}
and if so does the argument index need to match the parameter index?
if(isCat(b, a)) {
a.meow();// error
}
No error if matched index:
if(isCat(a, b)) {
a.meow();
}
I'm not sure of its's usefulness though.
Multiple arguments should be allowed.
I don't understand the example, though. What are the types of the unbound variables a and b in the bottom two code blocks?
a is of type Animal and b just a number. let's assume that isCat takes any as argument too.
Thanks @tinganho!
:clap: Thank you!
:smiley:
:clap: Great job @tinganho!
@jbondc The scenario you are describing is covered by #1003, not this feature.