three-ts-types icon indicating copy to clipboard operation
three-ts-types copied to clipboard

Can't narrow on `isOrthographicCamera`

Open rotu opened this issue 1 year ago • 4 comments

I have a property typed as PerspectiveCamera | OrthographicCamera.

Trying to distinguish based on camera type if (camera.isOrthographicCamera) doesn't work:

Property 'isOrthographicCamera' does not exist on type 'PerspectiveCamera | OrthographicCamera'. Property 'isOrthographicCamera' does not exist on type 'PerspectiveCamera'.(2339)

It would be nice to use this (and similar properties) as type discriminators by declaring them to be undefined on a base class?

rotu avatar Feb 01 '24 18:02 rotu

We could potentially augment the Camera class to add these properties, but it's worth noting that I don't believe the properties could be used as a way to narrow the type of a Camera to an OrthographicCamera (since properties can't be a type guard and Camera is not be a type union). Does that still make it worth it?

Methuselah96 avatar Feb 06 '24 14:02 Methuselah96

In my particular case, I have an object that types as a PerspectiveCamera | OrthographicCamera so it would help there.

But just about everything in this API has such a property flag and I'm looking for a more general solution.

Unfortunately, I think you're right that properties can't be a type guard per https://github.com/microsoft/TypeScript/issues/43368, so I don't think this can implemented in a tidy way.

rotu avatar Feb 28 '24 19:02 rotu

Actually, in guard DOES work, which seems kind of funny, since it's a less discerning check!

if ('isOrthographicCamera' in camera){
 // ...
}

rotu avatar Feb 28 '24 20:02 rotu

Yeah, that's probably the best option if you've got a union of specific camera implementations. Since adding the properties to the Camera is not particularly clean and it won't even allow type narrowing, I'm thinking it doesn't make sense for us to make any changes here. Let me know what you think.

Methuselah96 avatar Feb 29 '24 16:02 Methuselah96