Jared Beck
Jared Beck

Reputation: 17528

Sorbet signature for a function with class argument?

How do I write a signature for the following archive_all function?

sorbet.run

# typed: true
extend T::Sig

module Archivable
  def archive
  end
end
class Book
  extend Archivable
end
class Magazine
  extend Archivable
end

sig {params(klass: T.class_of(Archivable)).void}
def archive_all(klass)
  klass.archive
end

archive_all(Book) 
archive_all(Magazine)

Sorbet error:

editor.rb:17: Method archive does not exist on T.class_of(Archivable) https://srb.help/7003
    17 |  klass.archive
          ^^^^^^^^^^^^^
    editor.rb:5: Did you mean: Archivable#archive?
     5 |  def archive
          ^^^^^^^^^^^

Upvotes: 0

Views: 911

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369536

You want to be able to pass any instance of Archivable. The correct way to do this is to use a feature of Sorbet called a class type:

sig {params(klass: Archivable).void}

Observe.

Upvotes: 2

Related Questions