Assuming the following definition of x and y in a Pointer class:
x: number | undefined = undefined;
y: number | undefined = undefined;
Is there any way to give the class a function like this:
public isPointerReady(): this.x is number && this.y is number {
return this.x !== undefined && this.y !== undefined;
}
so in client code I could do something like this:
if (pointer.isPointerReady()) {
// can safely access pointer.x and pointer.y and use them as numbers
}
>Solution :
You can’t combine type predicates like (x is T) && (y is U). There’s an open feature request for it at microsoft/TypeScript#26916. You also can’t directly guard properties in type predicates like x.prop is T. There’s an open feature request for that also at microsoft/TypeScript#11117. Until and unless these are implemented, you’ll need to write your type guard method differently:
public isPointerReady(): this is { x: number, y: number } {
return this.x !== undefined && this.y !== undefined;
}
Here we are guarding this directly instead of this.x and this.y, but it has the same effect as what you were looking for:
const pointer = new Pointer();
pointer.x.toFixed(); // error! 'pointer.x' is possibly 'undefined'
pointer.y.toFixed(); // error! 'pointer.y' is possibly 'undefined'
if (pointer.isPointerReady()) {
pointer.x.toFixed(); // okay
pointer.y.toFixed(); // okay
}