Reputation: 1193
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]
Upvotes: 2
Views: 1238
Reputation: 377
You can try using Generic for the method definition.
Eg:
sig do
type_parameters(:U)
.params(
blk: T.proc.params(arg0: Elem).returns(T.type_parameter(:U)),
)
.returns(Box[T.type_parameter(:U)])
end
def map(&blk)
Box.new(blk.call(@x))
end
See example from sorbet.run
Upvotes: 2
Reputation:
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.
Upvotes: 5