0

我正在尝试让这个 Sorbet 代码正常工作(Sorbet 操场上):

# typed: true

extend T::Sig
extend T::Generic

class Foo
  extend T::Sig
  extend T::Generic

  TypeParam = type_member
end

class FooA < Foo
  TypeParam = type_member(fixed: Integer)
end

sig {type_parameters(:MyParam)
      .params(foo: Foo[T.type_parameter(:MyParam)]).void}
def blah(foo)
end

my_foo = FooA.new
blah(T.cast(my_foo, Foo[Integer]))

但是,我收到类型错误:

editor.rb:23: Expected Foo[T.type_parameter(:MyParam)] but found Foo[Integer] for argument foo https://srb.help/7002
    23 |blah(T.cast(my_foo, Foo[Integer]))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  Expected Foo[T.type_parameter(:MyParam)] for argument foo of method Object#blah:
    editor.rb:18:
    18 |      .params(foo: Foo[T.type_parameter(:MyParam)]).void}
                      ^^^
  Got Foo[Integer] originating from:
    editor.rb:23:
    23 |blah(T.cast(my_foo, Foo[Integer]))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Errors: 1

我不确定如何将blah方法单态化,以便它可以采用 type 的参数Foo[Integer]。Sorbet 目前是否支持此用例?

4

1 回答 1

0

如果我理解您要正确执行的操作,并且您只想接受blahtype的参数,则可以执行以下操作:Foo[Integer]

sig {params(foo: Foo[Integer]).void}
def blah(foo)
end

你可以看到一个完整的例子(类型不符合这里的接口):

class Foo
  extend T::Sig
  extend T::Generic

  TypeParam = type_member
end

class FooA < Foo
  TypeParam = type_member(fixed: Integer)
end

class FooB < Foo
  TypeParam = type_member(fixed: String)
end

sig {params(foo: Foo[Integer]).void}
def blah(foo)
end

my_foo = FooA.new
blah(my_foo)

my_bad_foo = FooB.new
blah(my_bad_foo)
于 2021-10-16T17:45:58.847 回答