Skip to content

Instantly share code, notes, and snippets.

@will
Last active October 23, 2020 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save will/6398d3c1e8c385f7a68429120e33db74 to your computer and use it in GitHub Desktop.
Save will/6398d3c1e8c385f7a68429120e33db74 to your computer and use it in GitHub Desktop.
sorbet and unexpected problems with &. operator and T.untyped
# 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