Search code examples
rubysorbet

How to specify type parameter


How to specify type parameter using sorbet?

For example, I want to annotate a method with an argument of type A returning generic type T[A].

def build_array(value) 
  [value]
end

The output type depends on the input type:

build_array(42) #=> return Array[Integer]
build_array('42') #=> return Array[String]

Solution

  • You can accomplish this using type_parameters:

    # typed: true
    extend T::Sig
    
    sig do
      type_parameters(:T)
      .params(value: T.type_parameter(:T))
      .returns(T::Array[T.type_parameter(:T)])
    end
    def build_array(value) 
      [value]
    end
    
    x = build_array(5)
    T.reveal_type(build_array(42))   # T::Array[Integer]
    T.reveal_type(build_array('42')) # T::Array[String]
    

    Here's a sorbet.run link with the above code.