Search code examples
rubysorbet

How to express empty hash


Is there any way to express the empty hash in Sorbet?

I have the attribute that has a well defined shape or is set to {}. Obviously T.type_alias({}) won't work because {} works as the Hash which is translated to T::Hash[T.untyped, T.untyped]. The easiest solution would be to have something like T.nil and then use it as T::Hash[String, T.nil] (fetching the value for the non-existing key will always return a nil value), but there is no such construction.

The workaround is to change the code to not accept the empty hash there and handle it differently. Then, it is possible to have T.nilable(SomeType). However, I would like to keep the code as it is now and just add a proper type signature.


Solution

  • I think you could use T::Hash[String, T.nilable(String)]? However when I try on sorbet.run, it seems to indicate that it won't type-check arguments of the method correctly.

    I have the attribute that has a well defined shape

    You may want to use T::Struct to represent this. Sorbet doesn't have great support for shape yet.

    T.nil

    You can use NilClass. It's actually a Ruby class.