Skip to content

RFC: Type Guards #124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Conversation

Bottersnike
Copy link

Rendered

Adds type guards of the form

function isFoo(x): x is Foo
    return x.type == "foo"
end

which can be used in control statements and assertions.

@deviaze
Copy link

deviaze commented May 31, 2025

Could we get this as a sort of typecast as well/instead? This could allow user-defined narrowing in a more natural inline manner.

For example:

type Entry = File | Directory | Symlink

local entry = getentry()
if str.endswith(entry.path, ".luau") :: entry is File then
    print(entry:read()) -- a method only on `File`
end

In this case we want to assume the entry is a File if it ends with .luau, but that isn't something inherent to the function str.endswith (which is just a substring check), but inherent to the logic of our conditional itself.

@Bottersnike
Copy link
Author

In terms of as well, I think that would be cool, though potentially worth a separate RFC. In terms of instead, you then lose many of the benefits of having dedicated guard functions, so I don't think I'd want to not have those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants