'What runtime code can I write to extract the type notations as defined by Sorbet, to display to the user?

Is there a way to inspect the type notations in ruby/sorbet?

I actually want to display those values in a form somewhere and instead of hardcoding in values like "this can be nil or a String", I want to instead use the code I've defined by the sig { ... }.

Example pseudo-code:

class User
  extend T::Sig
  sig { returns(T.nilable(String)) }
  def foo
    ...
  end
end

Sorbet.return_type(User, :instance_method, :foo) # returns '[nil, String]' or similar


Solution 1:[1]

I believe this is what I am looking for:

T::Utils.signature_for_method

In action:

T::Utils.signature_for_method(User.new.method(:daily?)).return_type
=> #<T::Types::Union:0x0000000132198da8
 @types=[#<T::Types::Simple:0x0000000132198f60 @name="TrueClass", @raw_type=TrueClass>, #<T::Types::Simple:0x0000000132198e98 @name="FalseClass", @raw_type=FalseClass>]>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander