id | title |
---|---|
tuples |
Tuples |
TODO: This page is still a fragment. Contributions welcome!
[Type1, Type2, ...]
This creates a fixed array type (also referred to as a tuple), which is a
fixed-length array with known types for each element. For example,
[String, T.nilable(Float)]
validates that an object is an array of exactly
length 2, with the first item being a String
and the second item being a
Float
or nil
.
Warning: Tuples have many known limitations, and should be considered an experimental feature. They may not work as expected or change without notice.
##
# Tuple types work for some simple cases,
# but have many known limitations.
#
extend T::Sig
sig {params(x: [Integer, String]).returns(Integer)}
def foo(x)
T.reveal_type(x[0]) # Revealed type: `Integer`
end
# --- What you expect ---
foo([0, '']) # ok
foo(['', 0]) # error: type mismatch
foo([]) # error: not right tuple type
# --- What you might not expect ---
foo([0, '', nil]) # ok
# --- Mutation: the ugly ---
y = [0, '']
y[0] = '' # ok (!)
T.reveal_type(y[0]) # Reveal type: `Integer(0)` (!!)
# --- Flow-sensitivity: even uglier ---
y_0 = y[0]
if y_0.is_a?(String)
puts y_0 # error: This code is unreachable (!!!)
end
sorbet internals note: the underlying of a tuple is an Array of the union of each element type.