0

如何指定String泛型类型?

→ 在 sorbet.run 上查看

# typed: strict


class NameList < Array
  extend T::Sig

  sig {params(names: T::Array[String]).void}
  def initialize(names)
    names.each { |n| self << n}
  end

  sig {returns(String)}
  def csv
    (map { |n| n.join(',') }).join("\n")
  end
end


nl = NameList.new(['Bruce', 'Clark', 'Peter'])

# Output length of first name.
puts(nl.first&.size)  # String#size
puts(nl.first&.sizee)  # misspelled size - should be an error

# Sorbet-Static output:
# editor.rb:4: Type Elem declared by parent Array must be re-declared in NameList https://srb.help/5036
#      4 |class NameList < Array
#         ^^^^^^^^^^^^^^^^^^^^^^
#     https://github.com/sorbet/sorbet/tree/master/rbi/core/array.rbi#L350: Elem declared in parent here
#      350 |  Elem = type_member(:out)
#             ^^^^^^^^^^^^^^^^^^^^^^^^
# Errors: 1
4

1 回答 1

0

您可以使用

Elem = type_member(fixed: String)

重新声明父类型成员已经是强制性的(您可以在代码片段上的错误消息中看到,它说Type Elem declared by parent Array must be re-declared in NameList)并使用参数重新声明它fixed:允许将该类型参数指定为具体类型。

→ 在 sorbet.run 上查看

# typed: strict

class NameList < Array
  extend T::Sig

  Elem = type_member(fixed: String)

  sig {params(names: T::Array[String]).void}
  def initialize(names)
    names.each { |n| self << n}
  end

  sig {returns(String)}
  def csv
    (map { |n| n.join(',') }).join("\n")  # Method `join` does not exist on String
  end
end


nl = NameList.new(['Bruce', 'Clark', 'Peter'])

# Output length of first name.
puts(nl.first&.size)
puts(nl.first&.sizee)  # Method `sizee` does not exist on String
于 2019-10-28T17:24:46.690 回答