如何表达空哈希

How to express empty hash

有什么方法可以在Sorbet中表达空散列吗?

我的属性具有明确的形状或设置为 {}。显然 T.type_alias({}) 不会起作用,因为 {} 用作 Hash,它被翻译成 T::Hash[T.untyped, T.untyped]。最简单的解决方案是使用 T.nil 之类的东西,然后将其用作 T::Hash[String, T.nil](获取不存在的键的值将始终 return 为 nil 值),但是没有这样的构造。

解决方法是更改​​代码以不接受那里的空哈希并以不同方式处理它。那么,就有可能有T.nilable(SomeType)。但是,我想保持代码不变,只添加一个适当的类型签名。

我想你可以使用 T::Hash[String, T.nilable(String)]?但是,当我尝试 sorbet.run 时,它似乎表明它不会正确 type-check 方法的参数。

I have the attribute that has a well defined shape

您可能还想使用 T::Struct to represent this. Sorbet doesn't have great support for shape

T.nil

你可以使用 NilClass。它实际上是一个 Ruby class.