#Unintentional Comparison, that is intentional...

1 messages · Page 1 of 1 (latest)

shell rapids
#

I am trying to write a tokenizer for calculator expressions. I have been following the examples of parsing in Bjarne Stroustrup's "The C++ Programming Language", translating my understanding to Typescript. The file attached is what I have so far.

The error I get is on line 122, "This comparison appears to be unintentional because the types calcEnum.LP and calcEnum.RP have no overlap

Yet through the recursive call to this.expression(true) it should always call this.getToken() eventually. Ensuring this.curToken is updated and requiring the evaluation.

Seeking suggestions for how to resolve this issue. Reading suggestions are welcome, when relevant.

thorn pivot
#

@shell rapids Yeah, I believe this is just a limitation of TS's flow analysis - it will preserve narrowings on object properties even if they might be invalidated by mutations.

shell rapids
#

This means as a solution I need to not assign within getToken and instead return, to then assign after?

thorn pivot
#

There's probably a solution that doesn't involve mutation like this, but I think mutation is pretty common for parsers.

shell rapids
#

As a newb, I am all ears for suggestions

thorn pivot
#

I know one trick I've seen is:

getCurToken() {
    return this.curToken;
}

And you'd do this.getCurToken() in place of this.curToken (at least in places where the compiler errors).

#

That works because TS won't apply narrowings to this.getCurToken(), it'll assume each call can return a different value.

shell rapids
#

hrm, that seems a good workaround

thorn pivot
#

... though it depends on how perf-critical this code is. There's a small overhead to function calls (would have to test if it gets optimized away) - if that's objectionable, I'm not sure there's a better approach than just some casting to get rid of the TS error.

shell rapids
#

This is a learning project, for certificaiton. There is nothing critical about it aside from my ability to demonstrate proficiency. Some day, I may get that elusive first position...

Ty for the information! Ill see what I can do with it. Ill holler more /resolve as needed

shell rapids
#

!resolved