首页 > 解决方案 > Sorbet:检查包含目标模块的类

问题描述

SorbetT.class_of可用于匹配后代类,但不能用于匹配包含模块的类:

module X; end
class A; end
class B < A; include X; end

B.ancestors # => [B, X, A, Object, PP::ObjectMixin, Kernel, BasicObject]

sig { params(x: T.class_of(A)).void }
def is_a(x); end

is_a(A)  # => ok
is_a(B)  # => ok

sig { params(x: T.class_of(X)).void }
def is_b(x); end

is_b(X)  # => ok
is_b(B)  # => error

根据https://sorbet.org/docs/class-of,这是因为 B 不是 X 的 singleton_class 的实例:

B.is_a?(A.singleton_class)  # => true
B.is_a?(B.singleton_class)  # => true
B.is_a?(X.singleton_class)  # => false

但没有提供替代建议。有没有办法根据类的祖先的内容进行类型检查?即类似的东西class_of可以用来检查模块中的类混合吗?

标签: sorbet

解决方案


推荐阅读