Type predicates with regex are unsound #2213
blutorange
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Type predicates generated by langium that include a regex are unsound. This is because type predicate are an if-and-only-if test: it returns true if and only if the value is of the given type. But the regex is not included in the TypeScript type. See e.g. microsoft/TypeScript#15048.
A type guard such as
will return
falseeven when the item is in fact anA(as far as TypeScript is concerned), e.g.isA("?").Possible solutions
Hard to solve without breaking compatibility. I didn't create an issue for now since I don't think anything can/will be done currently. I mainly wanted to point this out for now.
In principle, solutions could be to (a) drop the regex check or (b) drop the type predicate and make the return type only
boolean, or (c) generate both (a) and (b).Reproduction
Consider this grammar
This results in:
Now with these types, the following program type checks, but produces a runtime error due to mismatching types:
All reactions