Shopify / rubocop-sorbet

A collection of RuboCop rules for Sorbet
MIT License
183 stars 27 forks source link

Add cop to suggest `grep` over `select` when using only for type narrowing #247

Open vinistock opened 4 months ago

vinistock commented 4 months ago

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, 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)
andyw8 commented 4 months ago

Implementation notes (neither are critical for the first iteration):