r/ruby•
FooBarWidget

How to define circular type references in Sorbet?

Question

How do I make this work?

class Subscription < T::Struct
  const :transactions, T::Array[::Transaction]
end

class Transaction < T::Struct
  const :subscription, T.nilable(Subscription)
end

Right now Ruby errors at line 2 with "uninitialized constant Transaction (NameError)".

Posted Nov 2, 2022, 3:47 PM UTC

25
di3soft•

if that is in the same file it should be T::Array[Transaction]

1
FooBarWidgetOP•

It is in the same file. But Transaction is defined after Subscription and so T::Array[Transaction] does not work.

1
di3soft•

are the two classes defined another class? Added those two T struct to a random class of mine and it worked for me.

1
FooBarWidgetOP•

I don't know what you mean, can you post an example?

1
djudd1234•

This isn't really a Sorbet thing, except that T::Struct forces you to eagerly reference the other class. But one ugly workaround would be to re-open the class definitions:

class Subscription < T::Struct; end
class Transaction < T::Struct; end
class Subscription
const :transactions, T::Array[Transaction]
end
class Transaction
const :subscription, T.nilable(Subscription)
end

1