Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you use this in combination with is?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}

Playground link to code

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading