Sorbet type-checking on tree class with a custom schema?

113 views Asked by At

I have a custom tree-like class (MyTree) that stores data under hierarchical keys, (similar to filesystem paths). It exposes methods get and set, each of which operate on "."-separated keys. An instance of MyTree is given a schema when instantiated that specifies type for each key (for purposes of this question, consider the types of all values stored to be Nilable): each defined key:

t = MyTree.new({
  a: {
    b: { type: String },
    c: { type: Integer },
  },
  d: { type: Hash },
})

t.set('a.b', 'bar')
t.get('a.b')  # => 'bar'

I am trying to augment this class with sorbet, so that it would work like this:

# Sorbet type error (vaulue under a.b should be a `String`)
t.set('a.b', 3)

# Sorbet method error (`#length` doesn't exist on `Integer`)
t.set('a.c', 1)
x = t.get('a.c')
x.length

But I'm not sure how to make the schema for a given MyTree instance legible to sorbet. Is this possible?

0

There are 0 answers