ruby / ruby/rbs

Support type narrowing

Open
#1,822 2 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
2.2k
Forks
256
Avg merge
6d 17h
Merged PRs (30d)
37

Description

Ref: https://github.com/soutaro/steep/issues/472

Currently RBS doesn't have any syntax to narrow types in control flow.

So there's no way to achieve the following:

a = [1, nil].sample # a is `Integer | nil`
unless a.nil?
  # a is `Integer` here
  p a + 1
end

But actually, both Sorbet and Steep treat some special methods to narrow types

https://github.com/sorbet/sorbet/blob/718bc64f895abeeff88f56efbc92a3554ffaa4f2/infer/environment.cc#L536-L545

https://github.com/soutaro/steep/blob/a868762c2bd09f0954b05cdd9eab1819e14a51d3/lib/steep/interface/builder.rb#L709-L721

Ideally, I think we need to have a syntax considering Ruby gems which extend Object like ActiveSupport's present?.

I'm not very familiar with type system though, I guess the syntax would be similar with TypeScript's type predicates

https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

class Object[T?]
  def nil?: () -> self is nil
end
class Object[T?]
  def present?: () -> self is T
end

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the referenced Sorbet and Steep implementations, then inspect the RBS syntax and type-checking areas related to method signatures and control flow. The work is done when a reviewed syntax and behavior for type narrowing, including methods such as nil? and present?, is supported and tested.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.