Last active
October 23, 2020 17:21
-
-
Save will/6398d3c1e8c385f7a68429120e33db74 to your computer and use it in GitHub Desktop.
sorbet and unexpected problems with &. operator and T.untyped
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# typed: strict | |
class A | |
extend T::Sig | |
# many (nearly all?) return types from auto-generated | |
# rbi for gems are T.untyped | |
sig { returns T.untyped } | |
def num | |
3 | |
end | |
# same method, but not T.untyped | |
sig { returns Integer } | |
def num! | |
3 | |
end | |
end | |
extend T::Sig | |
sig {params(x: Integer).returns(String)} | |
def bar(x) | |
x.to_s | |
end | |
sig { returns T.nilable A } | |
def maybe_a | |
rand > 0.5 ? A.new : nil | |
end | |
# both have a type error: | |
# Method num (or num!) does not exist on NilClass component of T.nilable(A) | |
# and this makes sense, since `maybe_a` can be nil | |
bar maybe_a.num | |
bar maybe_a.num! | |
# no type error, even though `maybe_a` can be nil, and | |
# the `&.` operator will return nil in that case. | |
# This should be a type error, but the T.untyped swollows it | |
bar maybe_a&.num | |
# The only way to get a type error is to avoid accidently using methods | |
# that return T.untyped, and for gems this means manually writing rbi | |
bar maybe_a&.num! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment