【问题标题】:Recursive type_alias in sorbet冰糕中的递归 type_alias
【发布时间】:2022-02-08 23:16:33
【问题描述】:

如何声明一个可以包含对自身的引用的类型别名?例如,标记返回类似 JSON 结构的函数。

尝试:

Foo = T.type_alias { T.any(Integer, T::Array[Foo]) }

给出以下错误:

类型别名Foo参与循环

【问题讨论】:

    标签: ruby sorbet


    【解决方案1】:

    从 0.5.x 版本开始,这是不可能的,因为类型别名不支持循环。

    一种选择是降低结果的类型,然后直接实现:

    Foo = T.type_alias { T.any(Integer, T::Array[T.untyped]) }
    

    如果您真的想要进行类型检查,您可以通过将结果包装在 T::Struct 中来表达类似的内容。不过,这些对象将不再像原来那样平坦(参见sorbet.run):

    class Foo < T::Struct
      prop :content, T.any(Integer, T::Array[Foo])
    end
    
    myFoo = Foo.new(content: 1)
    content = myFoo.content
    case content
    when Integer
      puts "It was an integer!"
      T.reveal_type(content)
    when Array
      puts "It was a Foo!"
      T.reveal_type(content)
    else
      T.absurd(content)
    end
    

    编辑 (2022-02):type_alias 上的文档已更新以解决递归定义。它在sorbet.run 中包含一个类似 JSON 的结构的示例。

    【讨论】:

      猜你喜欢
      • 2019-07-08
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      相关资源
      最近更新 更多