Sorbet now supports proper type inference when narrowing types using grepsorbet.run.
This is a great improvement to ergonomics because it avoids having to cast the type after having already narrowed the elements of a collection. This is currently only supported for grep, since Sorbet can be sure of the behaviour, whereas select is more complex and allows for other conditions.
Let's add a cop that suggest using grep when select is being used exclusively for type narrowing:
strings_or_integers = T.let([], T::Array[T.any(String, Integer)])
# Bad. Sorbet cannot infer the right types when using `select`
strings_or_integers.select { |e| e.is_a?(String) }
# Good. The right types are inferred with `grep`
strings_or_integers.grep(String)
Sorbet now supports proper type inference when narrowing types using
grep
sorbet.run.This is a great improvement to ergonomics because it avoids having to cast the type after having already narrowed the elements of a collection. This is currently only supported for
grep
, since Sorbet can be sure of the behaviour, whereasselect
is more complex and allows for other conditions.Let's add a cop that suggest using
grep
whenselect
is being used exclusively for type narrowing: